Home > Article > Web Front-end > Js uses Canvas to compress images to explain the method
The following editor will bring you an article using JS to implement image compression function using Canvas. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
The APP project I recently worked on involves taking photos and uploading pictures with mobile phones. Because the pictures taken by mobile phones are usually relatively large, uploading will be very slow. For this reason, images need to be compressed to optimize the upload function. The following is the specific implementation:
/* * 图片压缩 * img 原始图片 * width 压缩后的宽度 * height 压缩后的高度 * 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 image data in base64 format. The larger the compression ratio value (between 0 and 1), the higher the picture quality. It is recommended not to convert the image to png format, because the base64 of the image is much longer than that of jpeg. The following is the actual call:
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 to the compression method and the image src assignment must be placed in the onload method of the image in. Because only after the image is loaded can it be compressed and converted to base64 for assignment. If placed outside the onload method, the compression code may be invalid, or a pure black image may be generated.
The above is the detailed content of Js uses Canvas to compress images to explain the method. For more information, please follow other related articles on the PHP Chinese website!