1 HTML
<van-uploader v-model="content" :before-read="(file) => beforeRead(content, file)" max-count="6" multiple />
2 JS
let content = ref([])
const beforeRead = (arr, file) => {
if (file.length) {
file.forEach((item) => {
imgCompress(item, (res) => {
arr.push({ file: item, url: res });
});
});
} else {
imgCompress(file, (res) => {
arr.push({ file, url: res });
});
}
}
function getBase64(file) {
// 上传图片转换base64
return new Promise(function (resolve, reject) {
let reader = new FileReader();
let imgResult = "";
reader.readAsDataURL(file);
reader.onload = function () {
imgResult = reader.result;
};
reader.onerror = function (error) {
reject(error);
};
reader.onloadend = function () {
resolve(imgResult);
};
});
}
function drawBeauty(beauty, width = 100, height = 100, fun) {
const imgWidth = width
const imgHeight = height
const canEle = document.createElement('canvas')
canEle.id = 'canvas'
canEle.setAttribute("hidden", true);
document.body.append(canEle)
var canvas = document.getElementById("canvas");
canvas.width = imgWidth
canvas.height = imgHeight
var ctx = canvas.getContext("2d");
ctx.drawImage(beauty, 0, 0, imgWidth, imgHeight);
const blob = canvas.toDataURL('image/jpeg', .75)
fun(blob)
// document.getElementById('img').src = blob
}
async function imgCompress(imgURI, fn) { // 图片压缩 imgURI:base64
// if( !/image/g.test(imgURI) ) return fn(imgURI); // 如果不是image
var beauty = new Image();
if (imgURI instanceof File)
beauty.src = await getBase64(imgURI);
if (beauty.complete) {
drawBeauty(beauty, beauty.width, beauty.height, fn);
} else {
beauty.onload = function () {
const value = drawBeauty(beauty, beauty.width, beauty.height, fn);
};
beauty.onerror = function () {
window.alert('图片加载失败,请重试');
};
};
}