前端实现压缩图片
<!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>
<div>
<input type="file" id='upload'/>
</div>
<script>
const upload = document.querySelector('#upload');
const ACCEPT = ['image/webp','image/png','image/jpeg'];
const MAXSIZE = 1024 * 1024 //1M
upload.addEventListener('change', e => {
const [file] = e.target.files; //相当于e.target.files[0]
if (!file) { //如果没有文件则返回
return;
}
//取出文件类型和文件大小,并取个别名
const {type: fileType, size: fileSize} = file;
//判断是否是允许上传的文件类型
if (!ACCEPT.includes(fileType)) {
alert(`不支持${fileType}文件类型`);
upload.value = ''
return;
}
//限制上传的大小
// if(fileSize > MAXSIZE) {
// alert('文件大于1M')
// upload.value = ''
// return;
// }
//把图片转换成base64
convertImageToBase64(file,(base64Image) => cpmpress(base64Image, uploadToServer))
})
function convertImageToBase64(file,callback) {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.addEventListener('load', e => {
const base64Image = e.target.result;
callback && callback(base64Image, uploadToServer);
reader = null;
})
}
function cpmpress (base64Image, callback) {
let maxW = 1024; //图片允许的宽
let maxH = 1024; //图片允许的高
const image = new Image(); //创建一个图片
image.src = base64Image;
// document.body.appendChild(image); // 如果需要在浏览器显示原图
image.addEventListener('load', e => {
let ratio,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;
maxH = image.naturalWidth / ratio;
}
//不需要压缩
if (!needCompress) {
maxW = image.naturalWidth;
maxH = image.naturalHeight;
}
const canvas = document.createElement('canvas'); //创建一个画布
canvas.setAttribute('id', '__compass__');
//设置宽高
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 compreeImage = canvas.toDataURL('image/jpeg', 0.9);
callback && callback(compreeImage)
//需要显示则打开
// canvas.remove()
})
}
function uploadToServer (compreeImage) {
//这里写上传的操作
console.log('===========');
}
</script>
</body>
</html>