图片压缩
作者:互联网
图片压缩
设置1M以上图片压缩
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<input type="file" id="upload" />
<script>
const upload = document.getElementById("upload");
const ACCEPT = ["image/jpg", "image/png", "image/jpeg","image/webp"];
const MAXSIZE = 1024 * 1024;
function convetImageToBase64(file, callback) {
let reader = new FileReader();
reader.addEventListener("load", function (e) {
const base64Image = e.target.result;
callback && callback(base64Image);
reader = null;
});
reader.readAsDataURL(file);
}
function compress(base64Image, callback) {
console.log(base64Image, "初始的base64");
let maxW = 1024;
let maxH = 1024;
const image = new Image();
image.addEventListener("load", function (e) {
let ratio; //图片的压缩比
let needCompress = false; //是否压缩
if (maxW < image.naturalWidth) {
needCompress = true;
ratio = image.naturalWidth / maxW;
maxH = image.naturalHeight / ratio;
}
if (maxH < image.naturalHeight) {
needCompress = true;
ratio = image.naturalHeight / maxH;
maxW = image.naturalWidth / ratio;
}
if (!needCompress) {
maxW = image.naturalWidth;
maxH = image.naturalHeight;
}
const canvas = document.createElement("canvas");
canvas.setAttribute("id", "__compress__");
canvas.width = maxW;
canvas.height = maxH;
canvas.style.visibility = "visibile";
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, maxW, maxH);
ctx.drawImage(image, 0, 0, maxW, maxH);
const compressImage = canvas.toDataURL("image/jpeg", 0.9);
callback && callback(compressImage);
const _image = new Image();
_image.src = compressImage;
document.body.appendChild(_image);
canvas.remove();
});
image.src = base64Image;
document.body.appendChild(image);
}
function uploadToServer(compressImage) {
console.log("上传", compressImage);
}
upload.addEventListener("change", (e) => {
const [file] = e.target.files;
if (!file) {
return;
}
const { type: fileType, size: fileSize } = file;
if (!ACCEPT.includes(fileType)) {
alert("不支持[" + fileType + "]类型");
upload.value = "";
return;
}
if (fileSize > MAXSIZE) {
alert(`文件超出1MB`);
}
//图片压缩
convetImageToBase64(file, (base64Image) =>
compress(base64Image, uploadToServer)
);
});
</script>
</body>
</html>
标签:canvas,const,压缩,maxW,maxH,base64Image,image,图片 来源: https://www.cnblogs.com/lht1132950411/p/16299901.html