CANVAS application-compressing and uploading images (for mobile browsers only ),
Recently, when I designed the Avatar upload function on the Mobile End, I used <input type = "file"> to upload images directly through formData. However, the actual usage is as follows: if the upload time of an excessively large image (such as a photo taken by a high-pixel mobile phone) is too long, the upload will fail, and each time the original size image is uploaded (the background is compressed), the user experience will be greatly affected, so I studied how to compress and upload images through canvas. The following are some ideas and experiences:
1. <input type = "file"> obtain the local image and draw the image into the canvas. The difficulty here is that, due to the browser's protection mechanism, you cannot directly obtain the image path of the local file. Therefore, you need to compile the local image into base64 format and upload it again. The Code is as follows:
Var result = document. getElementById ("/* error message display block */"); var input = document. getElementById ("/* Upload File tag */"); if (typeof FileReader === 'undefined') {result. innerHTML = "<p class = 'warn'> sorry, your browser does not support FileReader </p>"; input. setAttribute ('Disabled ', 'Disabled');} else {input. addEventListener ('change', readFile, false);} function readFile () {var file = this. files [0]; if (! /Image \/\ w + /. test (file. type) {alert ("Please make sure the file is of the image type"); return false;} var reader = new FileReader (); reader. readAsDataURL (file); reader. onload = function (e) {// this. result: The compiled image code can be directly displayed using src }}
2. Image Processing in canvas
Var c = document. getElementById ("/* canvas tag id */"); var cxt = c. getContext ("2d"); var img = new Image (); img. src =/* The obtained image encoding address */; var width = img. width; var height = img. height; dic = height/width; c. width = 200; // the image compression standard, which is calculated based on the fixed PX c. height = 200 * dic; cxt. clearRect (200,200, * dic); cxt. drawImage (img, 200,200, * dic); var finalURL = c. toDataURL (); // The finalURL is the compressed image encoding, which can be used to upload or directly generate an img tag.
Note the following points:
1. An error is reported during local debugging because of a cross-origin problem. You need to debug the problem on the server;
2. The drawImage () method in the canvas provides the image cropping function. However, if you write image stretching and cropping at the same time, the cropping method is prioritized;
3. When Using AJAX to upload image encoding, the plus sign in the encoding will be converted to a space for uploading, leading to background compilation failure;
4. The method for uploading images in the image area is still in the trial phase and will be supplemented later.