推荐一个不错的压缩工具插件compress.js,它可以压缩图片,还可以处理ios在拍照时方向不一致的兼容性。
接下来写一个压缩图片的方法:
// utils/compress.js
import Compress from "compress.js";
let compress = new Compress()
//格式转换方法
const base64ToBlob = function (base64Data, fileName) {
let arr = base64Data.split(','),
fileType = arr[0].match(/:(.*?);/)[1],
bstr = window.atob(arr[1]),
l = bstr.length,
u8Arr = new Uint8Array(l);
while (l--) {
u8Arr[l] = bstr.charCodeAt(l);
}
let blob = new Blob([u8Arr], {
type: fileType
});
return new window.File([blob], fileName, {
type: fileType
})
};
//图片压缩--可以支持数组的。目前只考虑一张图片
export default function (file) {
return new Promise((reslove, reject) => {
compress.compress(file, {
size: 1,
quality: .75,
resize: true,
rotate: false,
}).then((filebase) => {
const { prefix, data } = filebase[0]
const base64 = prefix + data
reslove(base64ToBlob(base64, file[0].name))
}).catch(err => {
reject(err)
})
})
}
在上传文件时引用他
import CImg from "@/utils/compress"
//压缩后的文件
const change = async (file) => {
//压缩后的图片
const CFile = await CImg([file])
}