In node. js (express), Jcrop is used to cut and upload images. node. jsjcrop

Source: Internet
Author: User

In node. js (express), Jcrop is used to cut and upload images. node. jsjcrop

Requirements

To put it simply, you need to upload an avatar and save the cropped parts as the Avatar.

Step 1: select the image:

 

Step 2: Display and crop in the pop-up window:

 

Step 3: click "save" to upload the file to the server.

Implementation Process

It is a bit bumpy, it is equivalent to doing it twice and taking a detour.

After 1st times, the user uploads the image and returns an address. Therefore, the image displayed on the bullet layer is already an image on the server, and then the image is cropped, save it.

One method found over 2nd times is thought of when cropping 1st times, that is, the bullet layer displays the images selected on the user's machine, and you do not need to upload them first, however, it is displayed using image/base64. In this way, there is one less interaction with the server, and the server does not need to store two images, it also improves the display speed on the bullet layer and provides a better experience, so it is an excellent solution.

The main technical points mentioned below:

Needless to say, the express framework is to post the cropped base64 data during storage, and write a corresponding route in the background.
Jquery does not need to be said. Page display control and ajax submission.

HTML5/FileReader/canvas, FileReader is used to read files as data, and we use its onLoad event. When canvas is used for cropping and moving, the cropped image is re-painted in real time (equivalent to Real-Time preview, of course, I have hidden it. I can display it during debugging. It can be hidden. The last uploaded is the base64 data of the canvas.

Jcrop plugin. This is a required cropping plug-in. Download and description here.
The other is to save the base64 string as an image, which is relatively simple on the server. Simply use fs. writeFile (fileName, dataBuffer, function (err.

Code

The view page mainly requires an upload control, as well as a canvas that defines the pop-up window div and the image used for re-painting the cropping range. Of course, the page should reference the corresponding js plug-in and css, mainly:

<Link rel = "stylesheet" href = "/css/jquery.Jcrop.css" rel = "external nofollow"> <script src = "/js/jquery. js "> </script> <script src ="/js/jquery. jcrop. js "> </script> <! -- Upload control --> <input type = "file" name = "upLoadImg1" id = "upLoadImg1"> <! -- Pop-up window and crop graph --> <div class = "cover">  <button id = "btnSave"> Save </button> </div> <! -- Re-paint the canvas within the cropping range --> <canvas id = "myCanva" width = "200" height = "200">

Js/jQuery, processing image loading and cropping upload.

First, we need to monitor the changes of the upload control. Because there is no button to trigger it here, we can directly monitor the change of upLoadImg1 to trigger it.

$ ('# UpLoadImg1 '). on ('change', function () {if (document. getElementById ("upLoadImg1 "). files. length = 0) {return;} var oFile = document. getElementById ("upLoadImg1 "). files [0]; if (! OFile) {return;} var fileName = oFile. name; var fileSize = oFile. size; var fileType = fileName. substring (fileName. lastIndexOf ('. '), fileName. length ). toLowerCase (); if (fileType! = '.Jpg '& fileType! = '.Jpeg '& fileType! = '.Gif '& fileType! = '.Png '& fileType! = '.Bmp ') {alert ("Select images in jpg, png, gif, and bmp Formats"); return;} if (fileSize> 2*1024*1024) {alert ('images up to 2 MB supported '); return;} var fileReader = new FileReader (); fileReader. readAsDataURL (oFile); // read fileReader successfully. onload = function (e) {// display pop-up window $ ('. cover '). show (); // set the image path in the pop-up window to base64 $ ('# Img1') of the selected image '). attr ('src', e.tar get. result); // The cropping component initializes initJcrop ();};});

Cropping should be initialized when it is displayed in the pop-up window:

Function initJcrop () {$ ('# Img1 '). jcrop ({onChange: updateCoords, onSelect: updateCoords, aspectRatio: 1, boxWidth: 300, boxHeight: 300}, function () {// The image size shown in the pop-up window var bb = this. getBounds (); var bWidth = Number (bb [0])/2; var bHeight = Number (bb [1])/2; // you can specify the crop range as this. setSelect ([0, 0, bWidth, bHeight]); // try {wdthScale = $ ('# Img1') ["0"]. width/222; heightScale = $ ('# Img1') ["0"]. height/238;} catch (e) {}jcrop_api = this ;});}

A very important pitfall is to define the global variables jcrop_api, widthScale and heightScale before that, the two scale variables are used to record the size of the selected original image and the scale-down/scale-up ratio of the displayed size on the pop-up window. For example, the image with a size of X is selected, however, the display range in the pop-up window is 222x238. This requires you to record the scaled-out multiple and multiply it by the cropped canvas, otherwise, the crop range is based on the 222x236 size, rather than the size of the original image. The preceding jcrop_api variable is used to re-select the image and destroy the last cropping initialization component.

Important events in the Jcrop component: onChange and onSelect are used to determine the coordinates (sizes) of the crop range. Therefore, it is also very important. In fact, the canvas is repainted here.

Function updateCoords (c) {var img = document. getElementById ('img1'); var ctx = document. getElementById ('mycanva '). getContext ('2d '); try {wdthScale = 1? $ ('# Img1') ["0"]. width/222: wdthScale; heightScale = 1? $ ('# Img1') ["0"]. height/238: heightScale;} catch (e) {}// draw the canvas ctx. drawImage (img, c. x, c. y, c. w * wdthScale, c. h * heightScale, 0, 0,200,200 );}

The other is to process the Save button. An ajax submits the base64 string of the image formed by the canvas, and the background can accept the save.

 var data = document.getElementById('myCanva').toDataURL(); $.ajax({  url: '/xxxx',  type: 'POST',  dataType: 'JSON',  cache: false,  data: {   'imgData': data  },  success: function(res) {},  error: function(err) {} });

This is all the process of uploading and cropping (Real-Time Preview.

The above is a small part of the node. jcrop is used in js (express) to cut and upload images. I hope it will be helpful to you. If you have any questions, please leave a message and the editor will reply to you in time. Thank you very much for your support for the help House website!

Related Article

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.