Js uses Canvas to compress images,
Recently, an APP project involves taking pictures on a mobile phone and uploading images. Because the pictures taken on a mobile phone are usually large, the upload process is slow. Therefore, image compression is required to optimize the upload function. The specific implementation is as follows:
/** Image Compression * img original image * width compression width * height compression height * ratio compression ratio */function compress (img, width, height, ratio) {var canvas, ctx, img64; canvas = document. createElement ('canvas '); canvas. width = width; canvas. height = height; ctx = canvas. getContext ("2d"); ctx. drawImage (img, 0, 0, width, height); img64 = canvas. toDataURL ("image/jpeg", ratio); return img64 ;}
The above is an image compression function that returns the image data in base64 format. The larger the compression ratio (between 0 and 1), the higher the image quality. We recommend that you do not convert an image into png format. Because it is converted into png format, the base64 ratio of the image to jpeg is much longer. The actual call is as follows:
var image = new Image();image.src = "/img/test.jpg"; image.onload = function(){ var img64 = compress(image, 500, 400, 0.7); document.getElementById("test").src = img64;}
Note: The call of the compression method and the image src assignment must be placed in the onload method of the image. Because the image can be compressed only after it is loaded, and then converted to base64 for assignment. If it is placed outside the onload method, the compression code may be invalid, or a pure black image will be generated.