当前位置:网站首页>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
边栏推荐
- [vulnhub range] - DC2
- RT-thread中关键词解释及部分API
- NPDP|产品经理如何做到不会被程序员排斥?
- Everything can be expected in the future | one 2022 campus recruitment officially opened
- BUUCTF WEB [BJDCTF2020]The mystery of ip
- leetcode-791. Custom string sorting
- How to prevent the website from being hacked and tampered with
- Zigbee之CC2530最小系统及寄存器配置(1)
- Message queuing overview
- mysql中 innoDB执行过程分析
猜你喜欢

Dialogue with Bruce, author of PostgreSQL: "changing careers" is to better move forward

Pre competition practice of TIANTI competition

leetcode:437. 路径总和 III【dfs 选还是不选?】

If you were a golang interviewer, what questions would you ask?

进程虚拟地址空间区域划分

Image attribute of input: type attribute of fashion cloud learning -h5

Object. The disorder of key value array after keys

Servlet监听器&过滤器介绍

在线计算过往日期天数,计算活了多少天

世界读书日:我想推荐这几本书
随机推荐
大家帮我看一下这是啥情况,MySQL5.5的。谢了
NPDP | how can product managers not be excluded by programmers?
At instruction of nbiot
21 天学习MongoDB笔记
只是不断地建构平台,不断地收拢流量,并不能够做好产业互联网
How to prevent the website from being hacked and tampered with
基于卷积神经网络的遥感影像分类识别系统
Object.keys后key值数组乱序的问题
Resolve disagrees about version of symbol device_ create
[daily question] chessboard question
[unity note] basic lighting in l4unity
AD20补充笔记3—快捷键+持续更新
leetcode:437. 路径总和 III【dfs 选还是不选?】
Luogu p5540 [balkanoi2011] timeismoney | minimum product spanning tree problem solution
Trier les principales utilisations de l'Agent IP réseau
Unlock openharmony technology day! The annual event is about to open!
【csnote】ER图
Aviation core technology sharing | overview of safety characteristics of acm32 MCU
Use source insight to view and edit source code
Plato farm - a game of farm metauniverse with Plato as the goal