Use Jcrop for picture trimming uploads in node. JS (Express)

Source: Internet
Author: User

Requirements Description

The simple thing is to implement the user to upload the avatar, and to save the user cut the part as the user picture.

The first step , select the picture:

The second step is to show and crop in the pop-up window:

Third Step , click "Save", upload the server.

Implementation process

Say a little bumpy, equivalent to do 2 times, took a detour.

The 1th time is the user selects the picture, has carried on the upload, then returns an address, therefore the picture which shows on the layer is already the picture on the server, then carries on the cutting, then saves.

The 2nd time to find a method, is in the 1th times to achieve the cutting process when thought, that is, the layer is displayed on the user machine selection of pictures, not first upload, but with image/base64 to show. This is a little interaction with the server, and the server does not store 2 times the picture, but also improve the performance of the projectile layer, experience better, so it is excellent.

The main technical points to be met:

    • Express Framework Needless to say, is the time to save the post-cutting base64 data, the background to write a corresponding route is good.
    • jquery does not have to say much, page display control and AJAX submissions.
    • Html5/filereader/canvas,filereader is used to read the file as data, we use its onLoad event, canvas, which is used as a trim move, redraws the cropped picture in real time (equivalent to real-time preview, of course I was hidden, When debugging can let him display), can hide, the last upload is actually this canvas's base64 data.
    • Jcrop plugin. This is the cut-off plug, necessary. Download and instructions here.
    • The other is Base64 string saved into a picture, which is relatively simple on the server, directly with the fs.writeFile(fileName,dataBuffer,function(err){}); good.
Specific code

View Page , the main need to have an upload control, as well as the definition of the pop-up div and canvas for redrawing the cropped range of images, of course, the page to refer to the corresponding JS plugin and CSS, and so on, mainly:

<link rel="stylesheet" href="/css/jquery." Jcrop.css "><script src="/js/jquery.js"></script><script src="/js/jquery." Jcrop.js "></script><!--upload controls --<input type="file" name= "upLoadImg1" id=" UpLoadImg1 "><!--pop-up window and crop graph --<div class="Cover">    <img id="IMG1" alt= "">    <button id="Btnsave">Save</button></div><!--trim Range redraw canvas--><canvas id="Mycanva" width="$" height=" ">

js/jquery, handles picture loading and cropping uploads.

The first thing to do is to monitor the change of the upload control, because we don't have a button to trigger it, so we can directly monitor it upLoadImg1 change .

$(' #upLoadImg1 '). On (' Change ', function() {    if(document.getElementById ("UPLOADIMG1"). Files.length = = =0) {return; }varOfile = document.getElementById ("UPLOADIMG1"). files[0];if(!ofile) {return; }varFileName = Ofile.name;varFileSize = ofile.size;varFileType = filename.substring (Filename.lastindexof ('. '), Filename.length). toLowerCase ();if(FileType! ='. jpg '&& FileType! ='. jpeg '&& FileType! ='. gif '&& FileType! ='. png '&& FileType! ='. bmp ') {alert ("Please select a picture in jpg,png,gif,bmp format");return; }if(FileSize >2*1024x768*1024x768) {alert (' maximum support for 2MB images ');return; }varFileReader =NewFileReader (); Filereader.readasdataurl (ofile);//successfully readFilereader.onload = function(e) {        //Show pop -up window$('. Cover '). Show ();//Set the picture path in the pop-up window to the base64 of the selected picture$(' #Img1 '). attr (' src ', E.target.result);//Trim Component InitializationInitjcrop (); };});

Trimming should be initialized when the popup is displayed:

 function initjcrop() {$(' #Img1 '). Jcrop ({onchange:updatecoords, onselect:updatecoords, Aspectratio:1, Boxwidth: -, Boxheight: -}, function() {        //The picture size shown in the pop-up window        varBB = This. getbounds ();varBwidth = Number(bb[0]) /2;varBheight = Number(bb[1]) /2;//Set initial selected crop range         This. Setselect ([0,0, Bwidth, Bheight]);//Raw picture reduction ratio        Try{Wdthscale = $ (' #Img1 ')["0"].width/222; Heightscale = $ (' #Img1 ')["0"].height/238; }Catch(e) {} JCROP_API = This; });}

A very important pit is that before you define global variables jcrop_api , widthScale and heightScale , 2 scale variables are used to record the size of the selected original picture with the size reduction/magnification on the pop-up window, for example, a picture of 1024x768 is selected, However, the scope of the pop-up window is 222x238, which needs to be reduced in multiples of the record, in the trimming of the canvas to be multiplied by this multiplier, or the scope of the crop is cut on this 222x236 size, rather than the size of the original picture cut. The preceding jcrop_api variable is used to re-select the picture when the last crop initialization component is destroy dropped.

JcropImportant events in the component: OnChange and Onselect, which determine the coordinates (dimensions) of the crop range, are also important, in fact, redrawing the canvas is done here.

 function updatecoords(c) {    varimg = document.getElementById (' IMG1 ');varCTX = document.getElementById (' Mycanva '). GetContext (' 2d ');Try{Wdthscale = Wdthscale = = = =1? $(' #Img1 ')["0"].width/222: Wdthscale; Heightscale = Heightscale = = =1? $(' #Img1 ')["0"].height/238: Heightscale; }Catch(e) {}//Draw canvas canvasCtx.drawimage (IMG, c.x, C.Y, C.W * wdthscale, c.h * Heightscale,0,0, $, $);}

The other is to handle the Save button, an AJAX to submit the canvas to form a picture of the Base64 string, the background to accept the save is OK.

var data = document.getElementById(‘myCanva‘).toDataURL(); $.ajax({     ‘/xxxx‘,     ‘POST‘,     ‘JSON‘,     false,     data: {         ‘imgData‘: data     },     function(res) {},     function(err) {} });

This is the whole process of uploading a crop (live preview).

Use Jcrop for picture trimming uploads in node. JS (Express)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.