Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use canvas to compress a picture in html5

2025-03-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use canvas to compress pictures in html5". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use canvas to compress pictures in html5".

Two days ago, I did a picture to base64 upload function, found that if the base64 of the picture is too large, the request will become very slow, serious direct timeout, so I thought of compressing the picture before uploading, and then uploading it to the background, which can greatly improve the efficiency. Record the several pits encountered using canvas to compress the picture here. The complete code will be given at the end of the article.

The first pit, when compressing the picture, did not get the width and height of the picture itself, and gave a fixed width of 600 to 480. Because it is on the mobile phone, it is a few megabytes of pictures when uploading pictures, so there is no problem with this piece. Where something went wrong, when the avatar was modified, the pictures uploaded during the test were all small pictures, and then the compressed pictures were not completely displayed, and most of them were blank. This is because the original width and height of the picture is not taken into account when compressing.

The second pit, the solution to the first pit is in the picture loading complete (onload), get the width and height of the picture itself, and then assign a value to canvas, so operation, but there is a pit is, picture loading is asynchronous, in your return, the return may be undefined rather than you need the compressed base64. The solution here is to create a new Promise, then return the result resolve (), and get the result when called.

Knowledge points:

ToDataURL of canvas ('image/png', 0.9); convert the picture drawn by canvas to base64, the first parameter indicates the type of image, and the second parameter represents the sharpness of the picture.

Specify a maximum size, if the width and height of the picture itself is greater than this size, scale according to the largest edge, the other is set according to the proportion of the picture, and then set to canvas.

MiniImage.js:

Export default async function miniSize (imgData, maxSize = 20001024) {/ / const maxSize = 200001024; if (imgData & & imgData.files & & imgData.files.size

< maxSize) { return imgData.url; }else{ console.log('----------------压缩图片-------------------'); const canvas = document.createElement('canvas'); let img = new Image(); img.src = imgData.url; let ctx = canvas.getContext('2d'); return new Promise((resolve =>

{img.addEventListener ('load', function () {/ / original size of the picture let originWidth = this.width; let originHeight = this.height; / / maximum size limit let maxWidth = 400, maxHeight = 400; / / Target size let targetWidth = originWidth, targetHeight = originHeight / / if (originWidth > maxWidth | | originHeight > maxHeight) {if (originWidth / originHeight > maxWidth / maxHeight) {/ / wider, 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 ('image/png', 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.length-1]); / / use .then () call to get the result await result.then (res = > {previous.push ({url: length});}) } else if (type = = "remove") {previous.splice (index,1) } await this.props.dispatch ({type: 'imagePicker/saveImage', payload: {files: previous}})} Thank you for reading. This is the content of "how to use canvas to compress pictures in html5". After the study of this article, I believe you have a deeper understanding of how to use canvas to compress pictures in html5. The specific use situation still needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report