当前位置:网站首页>Use compressorjs to compress pictures, optimize functions, and compress pictures in all formats
Use compressorjs to compress pictures, optimize functions, and compress pictures in all formats
2022-04-23 12:53:00 【ZMJ_ QQ】
The image compression function written in the last article is only applicable to
image/jpegandimage/webpImages .vue Achieve image compression , Support the compression of pictures when uploading multiple files ( Can only support jpeg)_ZMJ_QQ The blog of -CSDN BlogIn the actual development, there are other common picture formats png as well as ios Medium heic Image format , Need to compress pictures in all formats , Therefore, you can first convert the picture format to jpeg Reuse later compressorjs The compressed image .
1、ConvertImage.js Turn picture into jpeg Format
Reference blog input file Upload pictures and compress _ A blog named Mo Yu -CSDN Blog _input Upload compressed pictures
The method of this article directly adjusts canvas On canvas size , However, the image compressed by this method is seriously distorted
( There may be an easier way to convert the image format , If someone knows, leave a link for me , Hee hee )
// The idea is to create a picture , take file Equal to this picture , And then create a canvas Layers , take canvas Scale equally ,
// And then use canvas Of drawImage Match the picture with canvas Close , Then I'm putting canvas Of base64 Turn into file that will do
export default function ConvertImage(file) {
return new Promise((resolve, reject) => {
const fileName = file.name.substring(0, file.name.indexOf('.'));
let reader = new FileReader(); // Read file
reader.readAsDataURL(file);
reader.onloadend = function (e) {
let image = new Image() // Create a new one img label ( It's not embedded yet DOM node )
image.src = e.target.result // Set the path of the picture to file route
image.onload = function () {
let canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
imageWidth = image.width,
imageHeight = image.height,
data = ''
canvas.width = imageWidth
canvas.height = imageHeight
context.drawImage(image, 0, 0, imageWidth, imageHeight)
data = canvas.toDataURL('image/jpeg')
var newfile = dataURLtoFile(data, fileName + '.jpeg');
resolve(newfile)
}
}
})
}
function dataURLtoFile(dataurl, filename) { // base64 turn file object
let 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 File([u8arr], filename, { type: mime }); // Into the jpeg Format
}
2、ImageCompressor.js Compress the picture
import Compressor from 'compressorjs';
// Only right jpeg Format of the picture
/**
* @param image picture
* @param backType The type to be returned blob,file
* @param quality Picture compression ratio 0-1, The smaller the number is. , The smaller the picture compression
* @returns
*/
export default function ImageCompressor(image, backType, quality) {
return new Promise((resolve, reject) => {
new Compressor(image, {
quality: quality || 0.6,
success(result) {
let file = new File([result], image.name, { type: image.type })
if (!backType || backType == 'blob') {
resolve(result)
} else if (backType == 'file') {
resolve(file)
} else {
resolve(file)
}
},
error(err) {
console.log(' Picture compression failed ---->>>>>', err)
reject(err)
}
})
})
}
3、 Use
If the picture is not jpeg For format, first convert the file , Compress after successful conversion
import ImageCompressor from '@/utils/ImageCompression';
import ConvertImage from '@/utils/ConvertImage';
async getUrl(file) {
this.isShowLoading = true;
const formData = new FormData();
for (let i = 0; i < file.length; i++) {
let img = file[i];
const fileType = img.name.substring(img.name.indexOf('.') + 1);
// Determine if the file is jpeg No jpeg Everything turned into jpeg
if (!['jpeg', 'jpg'].includes(fileType)) {
img = await ConvertImage(img); // Turn to Chen jpeg Format file
}
let newImg = await ImageCompressor(img, 'file', 0.6); // Picture compression
formData.append('file', newImg);
}
multipleFiles(formData).then((res) => {
//axios Upload .....
});
},
版权声明
本文为[ZMJ_ QQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230616456984.html
边栏推荐
- CGC: contractual graph clustering for community detection and tracking
- Bert base Chinese Download (SMART)
- 硬核解析Promise对象(这七个必会的常用API和七个关键问题你都了解吗?)
- MySQL function - recursive function
- XinChaCha Trust SSL Organization Validated
- If you were a golang interviewer, what questions would you ask?
- Labels and paths
- SSL certificate refund instructions
- 使用Source Insight查看编辑源代码
- leetcode-791. Custom string sorting
猜你喜欢
随机推荐
21 天学习MongoDB笔记
At instruction of nbiot
A graphic designer's fantasy world | ones characters
8 websites that should be known for product development to enhance work experience
How to prevent the website from being hacked and tampered with
航芯技术分享 | ACM32 MCU安全特性概述
Get the punch in record of nailing attendance machine
【蓝桥杯】4月17日省赛刷题训练(前3道题)
力扣刷题之完全二叉树的节点个数
A graphic designer's fantasy world | ones characters
Web17 -- use of El and JSTL
NBIOT的AT指令
Image attribute of input: type attribute of fashion cloud learning -h5
[unity note] basic lighting in l4unity
SSM framework series - data source configuration day2-1
只是不断地建构平台,不断地收拢流量,并不能够做好产业互联网
Recommended website for drawing result map
Customize the shortcut options in El date picker, and dynamically set the disabled date
21 days learning mongodb notes
leetcode:437. Path sum III [DFS selected or not selected?]







![[csnote] ER diagram](/img/97/82e8c2183fcafda50950a953ca0955.png)

![[unity note] basic lighting in l4unity](/img/38/d88245af2062ed67fb8e61327f3bb9.png)