HTML5 file API plus canvas for image front-end JS compression and upload (reprint)

Source: Internet
Author: User
Tags webp

First, image upload front-end compression of practical significance

For large-size image upload, in the front-end compression in addition to save traffic, the greatest significance is greatly improved user experience.

This experience includes two things:

    1. Because the upload image size is relatively small, so the upload speed will be faster, the interaction will be more fluent, while greatly reducing the network anomaly caused the upload failure risk.
    2. The most important point of experience Improvement: omitting the cost of reprocessing the image. Many of the site's image upload function will be limited to the size of the picture, especially the Avatar upload, limit 5M or 2M is very common. And now the digital device shooting features are very outstanding, a raw image more than 2M almost standard, at this time if users want to put a mobile phone or camera in a proud image upload as their avatar, will encounter because of the size of the picture can not upload the dilemma, have to re-process the picture, And this experience is actually very bad. If you can compress on the front end, it is not necessary to theoretically limit the size of the picture.
Second, the picture front-end JS compression and upload function experience

Specially made a picture front-end compression and upload the full demo, you can ruthlessly click here: Use canvas to compress images in the front and upload the demo

Enter the demo to see a plain File entry box:

Ah, no, it should be this picture:

Click on the File selection box, we may wish to choose a larger size of the picture, such as the following 2M fishing Harvest photos:

So the picture 歘 歘 歘 to pass up:

At this point we click the final uploaded image address, we will find that the original 2M more than 3,000 pixels wide picture is limited to 400 pixels wide:

Save to Local will find that the image size has become only 70K:

The above is the picture front-end compression and upload demo full demo.

Third, HTML5 file API plus canvas implementation of the picture front-end JS compression

To use JS to achieve the compression effect of the picture, the principle is very simple, the core API is canvas the drawImage() method used.

canvasThe drawImage() method API is as follows:

Context.drawimage (Img,sx,sy,swidth,sheight,x,y,width,height);

Although it looks like there are 9 parameters, but don't panic, you can actually see the 3 parameters:

Img
is a picture object, either a DOM object that gets on the page or a picture object in the virtual DOM.
Sx,sy,swidth,sheight
Draw an area on the canvas to place the picture in the upper canvas sx,sy -left corner, referring to the size of the swidth,sheight area. If you do not specify the next 4 parameters, the picture is stretched or scaled within the area.
X,y,width,height
is canvas the size and position of the picture displayed on the canvas. If the width,height value here is the original size of the picture, the final result is that the picture is clipped within the swidth,sheight area.

For the image compression of this article, the last four parameters are not available, cancel the first five parameters on it. For example, a picture (assuming the image object is img ) The original size is 4000*3000, now need to limit the size to 400*300 size, very simple, the principle is as follows code:

var canvas = document.createelement (' canvas '); var context = Canvas.getcontext (' 2d '); canvas.width = 400;canvas.height = 300;//Core JS on this context.drawimage (img,0,0,400,300);

Draw a large picture directly on a small canvas. At this time the big picture will naturally become a small picture, compression is so realized, is not simply a bit beyond imagination.

Of course, to be on the ground in the actual development, we also need to do some other work, is to solve the picture source and picture whereabouts of the problem.

1. How do I present the pictures in the system to the browser?

The HTML5 file API allows images to be displayed directly in the browser before uploading, usually using a FileReader method that shows the following code:

var reader = new FileReader (), img = new Image ();//Read file successful callback reader.onload = function (e) {  ///E.target.result is the base6 of the picture 4 address information  img.src = E.target.result;}; Elefile.addeventlistener (' Change ', function (event) {    reader.readasdataurl (event.target.files[0]);});

So, the picture in the method containing the picture information is context.drawImage() img there.

2. If you convert the canvas canvas to an IMG image
canvasNatural offers 2 ways to turn pictures, one is:

Canvas.todataurl () method
The syntax is as follows:

Canvas.todataurl (MimeType, qualityargument)

The image can be converted into base64 format information, the pure character of the picture notation.

which
mimeTypeThe type of the image to be shown, the canvas base64 default is PNG format, which is the default value ‘image/png‘ , we can also be specified as JPG format ‘image/jpeg‘ or WEBP format. The file object file.type is the mimetype type of the file, which can be used directly when converting (if there is a file object).
qualityArgumentRepresents the exported picture quality, as long as the export to jpg and webp format the time this parameter has effect, the default is 0.92 , is a more reasonable picture quality output parameters, usually, we do not need to set.

Canvas.toblob () method
The syntax is as follows:

Canvas.toblob (Callback, MimeType, Qualityargument)

You can convert a canvas into a blob file, usually in a file, because it is binary and more friendly to the backend.

Compared with the toDataURL() method, the toBlob() method is asynchronous, so there are a number of callback parameters, this callback callback method by default, the first parameter is the conversion of good blob file information, the file upload of this document is to canvas convert the image into a binary blob file, and then ajaxuploaded, the code is as follows:

Canvas to Blob and upload canvas.toblob (function (BLOB) {  //image Ajax upload  var xhr = new XMLHttpRequest ();  Start uploading  xhr.open ("POST", ' upload.php ', true);  Xhr.send (BLOB);    });

So, after the "picture →canvas compression → picture" Three steps, we completed the picture front-end compression and upload function.

A more complete core code can be found on the left side of the demo page, if you are interested in other interactive code, please refer to the page source code.

Iv. concluding remarks

Just a few months ago wrote an article "using Canvas to achieve image watermark synthesis at the front end," In fact, the technology and routines used in this article is the same, but also "picture →canvas watermark → picture" three-step, the difference is that the watermark is the synthesis of two consecutive context.drawImage() methods, Once is the original image watermark picture, and finally converted into a picture of what is the toDataURL() method, the other code logic and principle are the same.

Sichun, using the same principles and code logic, we can also implement many other functions that were not well implemented by the front end, such as the true clipping effect of the image, the so-called "true tailoring" refers to the overflow:hidden clip "pseudo-clipping" of the CSS properties, but rather the large area image information. Even with some front-end algorithms, we can directly in the front-end face recognition, image automatic beautification, such as a series of functions, such as uploading.

The principle is the same, are used canvas as intermediate medium for processing.

OK, the above is the whole content of this article, thank you for reading, welcome error correction, Welcome to Exchange!

HTML5 file API plus canvas for image front-end JS compression and upload (reprint)

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.