Home  >  Article  >  Web Front-end  >  Js+Canvas makes image compression

Js+Canvas makes image compression

php中世界最好的语言
php中世界最好的语言Original
2018-04-17 11:33:291277browse

This time I will bring you Js Canvas to make image compression, Js Canvas to make image compression What are the precautions, the following is a practical case, let's come together take a look.

/* 
 * 图片压缩
 * 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");            
   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. Here 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. 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.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

angularJS Ionic uploads images on the mobile terminal (with code)

Particles.js implements particles Dynamic background animation

The above is the detailed content of Js+Canvas makes image compression. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn