Js uses Canvas to compress images,

Source: Internet
Author: User

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.

 

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.