/common/compressImage/convertImage
// 思路是创建一个图片,将file等于这个图片,然后创建一个canvas图层 ,将canvas等比例缩放,
//然后用canvas的drawImage将图片与canvas合起来,然后在把canvas的base64转成file即可
export default function ConvertImage(file) {
return new Promise((resolve, reject) => {
const fileName = file.name.substring(0, file.name.indexOf('.'))
let reader = new FileReader() //读取file
reader.readAsDataURL(file)
reader.onloadend = function (e) {
let image = new Image() //新建一个img标签(还没嵌入DOM节点)
image.src = e.target.result //将图片的路径设成file路径
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转file对象
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 }) //转成了jpeg格式
}
/common/compressImage/compressorjs.js
import Compressor from 'compressorjs' // npm 下载包
/**
* @param image 图片
* @param backType 需要返回的类型blob,file
* @param quality 图片压缩比 0-1,数字越小,图片压缩越小
* @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('图片压缩失败---->>>>>', err)
reject(err)
},
})
})
}
使用1:封装方法
async getUrl(file) {
this.isShowLoading = true;
for (let i = 0; i < file.length; i++) {
let img = file[i];
const fileType = img.name.substring(img.name.indexOf(".") + 1);
// 判断文件是不是jpeg 不是jpeg的都转成jpeg
if (!["jpeg", "jpg"].includes(fileType)) {
img = await ConvertImage(img); //转陈jpeg格式的file
}
let newImg = await ImageCompressor(img, "file", 0.6); //图片压缩
// newImg 压缩后文件 File
}
},
以上来源
使用2:不封装方法,直接用
<script>
// ...
import ImageCompressor from "../../common/compressImage/compressorjs.js";
import ConvertImage from "../../common/compressImage/convertImage";
export default {
name: "addCar",
methods: {
jszxszUpload(type) {
uni.chooseImage({
success: async (imageRes) => {
let bool = true;
if (imageRes.tempFiles[0].type) {
if (
!["image/jpeg", "image/jpg", "image/png", "image/heic"].includes(
imageRes.tempFiles[0].type
)
) {
bool = false;
}
} else {
const imgTypeStr = "jpeg, jpg, png, heic";
const type = imageRes.tempFilePaths[0].split(".")[1];
if (imgTypeStr.indexOf(type.toLowerCase()) < 0) {
bool = false;
}
}
if (!bool) {
uni.showLoading({
title: "请上传 jpeg、jpg、png、heic 格式图片",
icon: "none",
});
setTimeout(function () {
uni.hideLoading();
}, 2000);
return;
}
let fileBase64 = "";
//#ifdef H5
/** ** 图片压缩 start ****/
let img = imageRes.tempFiles[0];
const fileType = img.name.substring(img.name.indexOf(".") + 1);
if (!["jpeg", "jpg"].includes(fileType)) {
img = await ConvertImage(img); // 转为 jpeg 格式的 file
}
let newImg = await ImageCompressor(img, "file", 0.6); //图片压缩
/** ** 图片压缩 end ****/
fileBase64 = await this.toBase64(newImg);
//#endif
//#ifdef MP-WEIXIN
/** ** 图片压缩 start ****/
let imgBlob = imageRes.tempFilePaths[0];
const fileTypeBlob = imgBlob.name.substring(
imgBlob.name.indexOf(".") + 1
);
if (!["jpeg", "jpg"].includes(fileTypeBlob)) {
imgBlob = await ConvertImage(imgBlob); // 转为 jpeg 格式的 file
}
let newImgBlob = await ImageCompressor(imgBlob, "blob", 0.6); //图片压缩
/** ** 图片压缩 end ****/
fileBase64 = await this.downloadAndConvert(newImgBlob);
//#endif
// ... 以 base64 格式上传图片 fileBase64
},
});
},
// 文件转base64
toBase64(file) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = (e) => {
resolve(e.target.result);
};
fileReader.readAsDataURL(file);
fileReader.onerror = () => {
reject(new Error("文件流异常"));
};
});
},
},
};
</script>