Recently, the company has a requirement that the size of uploaded pictures should be 10MB and the pictures uploaded by users should be compressed in the upload. Baidu has checked some information.
The solution is to use Canvas for image compression. The second parameter of Canvas toDataURL method is image quality, and different image quality is used to achieve the compression effect.
Technology stack: vue/ Element /canvas…
————————————————————————————————
steps
- Get the base64 format of the picture;
- After the picture is loaded, the picture is drawn to canvas for compression.
- Through canvas toDataURL method to achieve compression;
- Upload images and convert dataURL into Bolb objects;
- Add Bold to the formData object;
- Determine the Blod size and upload the background service
No more nonsense to say directly on the code ~~~
1 Entrance Method
MinEvent (file) {//element-ui upload component before-upload method let that = this; Let reader = new FileReader(); let reader = new FileReader(); / / read from the console. The log (file); reader.readAsDataURL(file); reader.onload = function () { let content = this.result; // Let img = new Image(); img.src = content; PressEvent (img, (dataURL) => {that.uploadimg (dataURL, file); }); }; }; }Copy the code
2. Compress images through Canvas
//通过canvas 进行图片压缩 compressEvent(img, callback) { let that = this; let canvas = document.createElement("canvas"); let ctx = canvas.getContext("2d"); let initSize = img.src.length; let width = img.width; let height = img.height; canvas.width = width; canvas.height = width / (width / height); //等比例缩缩放图片 ctx.drawImage(img, 0, 0, width, height); let dataURL = canvas.toDataURL("image/jpeg", 0.5); // 0.7 为图片质量 图片质量0~1默认值0.92 that.img = dataURL; callback ? callback(dataURL) : null; //调用回调函数 }
Copy the code
3 Images are converted into BLOB objects
DataURItoBlob (dataurl) {//dataurl is base64 format var arr = dataurl.split(","), mime = arr[0].match(/:(.*?) ; /)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); }Copy the code
4 Uploading pictures
uploadImg(dataURL, file) { let that = this; let blob = that.dataURItoBlob(dataURL); let formData = new FormData(); formData.append("file", blob, file.name); console.log(blob.size / 1024 / 1024); If (blob.size > 10 * 1024 * 1024) {alert(" image size over 10M"); return false; } // Upload code omitted}Copy the code