创建一个type="file"的input标签,用于文件上传。
<input type="file" name="" id="upload" value="" />
通过js实现图片压缩
window.onload = function () {
const upload = document.getElementById("upload");
upload.onchange = uploadImage;
};
// 图片上传
function uploadImage(event) {
const file = event.target.files[0];
console.log(file, "未压缩的图片file")
createImage(file, async function (img) {
createCanvas(img, 1200, file, async function (newFile) {
console.log(newFile, "压缩后的图片")
});
});
}
// 生成图片副本
// 将file通过FileReader 转换为base64格式
async function createImage(file, callback) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
const img = new Image();
img.src = reader.result;
callback(img);
};
}
// 通过canvas绘制图片
function createCanvas(img, max, file, callback) {
const cvs = document.createElement("canvas");
const ctx = cvs.getContext("2d");
let width = img.naturalWidth || 400;
let height = img.naturalHeight || 400;
const ratio = width / height;
if (width > max) {
width = max;
height = width / ratio;
}
cvs.width = width;
cvs.height = height;
img.onload = async function () {
// 降低图片质量
const base64 = await compressImage(cvs, ctx, img, width, height, max);
// base64转成blod格式文件
const BlobData = await convertBase64UrlToBlob(base64);
// blod格式文件转成file格式并返回
const this_file = new File([BlobData], file.name, {
type: file.type,
});
callback(this_file);
};
}
// 图片质量压缩
// 通过canvas.toDataUR()降低图片质量
async function compressImage(cvs, ctx, img, width, height, max) {
// 图像质量 quality值越小,所绘制出的图像越模糊
var quality = 0.7;
var anw = document.createAttribute("width");
anw.nodeValue = width;
var anh = document.createAttribute("height");
anh.nodeValue = height;
cvs.setAttributeNode(anw);
cvs.setAttributeNode(anh);
ctx.drawImage(img, 0, 0, width, height);
var base64 = cvs.toDataURL("image/jpeg", quality);
return base64;
}
// base64转成blod格式文件
async function convertBase64UrlToBlob(urlData) {
var arr = urlData.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 Blob([u8arr], { type: mime });
}
最终实现的效果如图所示