Home  >  Article  >  Web Front-end  >  Sample code for html5 using canvas to compress images

Sample code for html5 using canvas to compress images

青灯夜游
青灯夜游forward
2018-10-08 17:34:272973browse

This article mainly introduces the relevant information about the sample code of HTML5 using canvas to compress images. The editor thinks it is quite good, so I will share it with you now and give it as a reference.

I made a function to convert images to base64 for upload two days ago. I found that if the base64 of the image is too large, the request will become very slow, and it will time out seriously, so I thought of compressing the image before uploading. , and then upload it to the background, which can greatly improve efficiency. Here are some pitfalls encountered when using canvas to compress images. The complete code will be given at the end of the article.

The first pitfall is that when compressing the image, the width and height of the image itself are not obtained, and a fixed width and height of 600*480 are given. Because it is on the mobile phone, when uploading the image, it is always several megabytes. picture, so there is no problem with this. The problem occurred when modifying the avatar. The pictures uploaded during the test were all small pictures, and then the compressed pictures were not displayed completely, and most of them were blank. This is because they were not considered during the compression. The original width and height of the picture.

The second pitfall, the way to solve the first pitfall is to get the width and height of the image itself after the image is loaded (onload), and then assign it to canvas, and operate in this way, but there is a pitfall. , image loading is asynchronous, when you return, what is returned may be undefined instead of the compressed base64 you need. The solution here is to create a new Promise, then resolve() returns the result, and .then() gets the result when calling.

Knowledge points:

  • canvas' toDataURL('image/png', 0.9); Convert the image drawn by canvas to base64, No. One parameter represents the type of picture, and the second parameter represents the clarity of the picture.

  • Specifies a maximum size. If the width and height of the image itself are larger than this size, it will be scaled according to the largest side, and the other will be set according to the proportion of the image, and then set to canvas.

miniImage.js

export default async function miniSize(imgData, maxSize = 200*1024){
    // const maxSize = 200 * 1024;

    if(imgData && imgData.files && imgData.files.size < maxSize) {
        return imgData.url;
    }else{
      console.log(&#39;----------------压缩图片-------------------&#39;);
      const canvas = document.createElement(&#39;canvas&#39;);
      let img = new Image();
      img.src = imgData.url;
      let ctx = canvas.getContext(&#39;2d&#39;);
      return new Promise((resolve =>{
        img.addEventListener(&#39;load&#39;, function(){
          //图片原始尺寸
          let originWidth = this.width;
          let originHeight = this.height;
          // 最大尺寸限制
          let maxWidth = 400, maxHeight = 400;
          // 目标尺寸
          let targetWidth = originWidth, targetHeight = originHeight;
          // 图片尺寸超过400x400的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更宽,按照宽度限定尺寸
              targetWidth = maxWidth;
              targetHeight = Math.round(maxWidth * (originHeight / originWidth));
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(maxHeight * (originWidth / originHeight));
            }
          }
          canvas.width = targetWidth;
          canvas.height = targetHeight;
          ctx.drawImage(img, 0, 0, targetWidth, targetHeight);
          let base64 = canvas.toDataURL(&#39;image/png&#39;, 0.9);
          resolve(base64);
        }, false);
      }))
    }
}

Call:

test.js

onChangeImg = async (files, type, index) => {
    let previous = this.props.imagePicker.files;
    if(type === "add") {
      let result = miniSize(files[files.length-1]);
      //使用 .then() 调用获得结果
      await result.then(res => {
         previous.push({url: res});
      });
    }else if(type === "remove") {
        previous.splice(index,1);
    }
    await this.props.dispatch({
      type: &#39;imagePicker/saveImage&#39;,
      payload: {
        files: previous
      }
    })
  }

The above is the entire content of this article, I hope it will be helpful to everyone Learning helps!

The above is the detailed content of Sample code for html5 using canvas to compress images. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete