<!DOCTYPE html>
<html lang="zh-CN">
<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>Canvas图片压缩</title>
</head>
<body>
<div>
<input id="upload" type="file" accept=".png,.jpg,.jpeg">
</div>
<script>
const ACCEPTS = ['image/png', 'image/jpg', 'image/jpeg'];
const MAXSIZE = 3 * 1024 * 1024;
const MAXSIZE_STR = '3MB';
function convertImg2Base64(file, callback) {
if (!file) return;
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) {
if (!base64Image) return
let maxW = 1080;
let maxH = 720;
const image = new Image();
image.addEventListener('load', function(e) {
let ratio; // 图片压缩比
let needCompress = false; // 是否需要压缩标识
// 宽度超出设置进行压缩
if (image.naturalWidth > maxW) {
needCompress = true
ratio = image.naturalWidth / maxW;
maxH = image.naturalHeight / ratio;
}
// 高度超出设置进行压缩
if (image.naturalHeight > maxH) {
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 = 'visible';
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(document.createElement('div').innerHTML = 'canvas压缩图:');
document.body.appendChild(_image);
canvas.remove();
})
image.src = base64Image;
image.style.width = '1080px';
image.style.height = '720px';
document.body.appendChild(document.createElement('div').innerHTML = '原图:');
document.body.appendChild(image);
}
function uploadToServer(compressImage) {
console.log('--uploadToServer--');
}
const upload = document.getElementById('upload');
upload.addEventListener('change', function(e) {
const [file] = e.target.files;
if (!file) return;
const { type: fileType, size: fileSize} = file; // ES语法,对结构的值进行重命名
// 文件类型校验
if (!ACCEPTS.includes(fileType)) {
alert(`不支持${fileType}文件类型`);
upload.value = '';
return;
}
// 文件大小校验
if (fileSize > MAXSIZE) {
alert(`文件超出${MAXSIZE_STR}!`);
upload.value = '';
return;
}
convertImg2Base64(file, (base64Image) => compress(base64Image, uploadToServer));
})
</script>
</body>
</html>
主要Canvas画图,对图片宽高重设,输出画布图像时设置质量,达到减小图片大小的目的。