原生JS压缩图片
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js压缩图片</title>
</head>
<body>
<img id="img" src="">
<input id="file" type="file" onchange="upload()">
</body>
<script>
async function upload() {
let fileObj = document.getElementById('file').files[0]
try {
let imageSize = await beforeUpload(fileObj)
if (imageSize) {
let initSize = (fileObj.size / 1024).toFixed(2)
let reader = new FileReader()
reader.readAsDataURL(fileObj)
reader.onload = function(e) {
let image = new Image()
image.src = e.target.result
image.onload = function() {
let setImg = compressImg(image, fileObj)
document.getElementById('img').src = setImg
if (getImgSize(setImg) < (initSize * 1024)) {
console.log('长传压缩后的图片')
} else {
console.log('长传原图')
}
}
}
}
} catch (e) {
console.log(e);
}
}
function compressImg(img, fileObj, quality = 0.7, width = 1, height = 1) {
let canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
imageWidth = img.width / width,
imageHeight = img.height / height,
result = '';
canvas.width = imageWidth
canvas.height = imageHeight
context.drawImage(img, 0, 0, imageWidth, imageHeight)
result = canvas.toDataURL('image/jpeg', quality)
return result
}
function getImgSize(base64url) {
var str = base64url.replace('data:image/jpeg;base64,', '');
var strLength = str.length;
var fileLength = parseInt(strLength - (strLength / 8) * 2);
var size = "";
size = (fileLength / 1024).toFixed(2)
return parseInt(size);
}
const getFileWidthAndHeight = (file, initwidth, initheight) => {
return new Promise((resolve, reject) => {
let width = initwidth;
let height = initheight;
let _URL = window.URL || window.webkitURL;
let img = new Image();
img.src = _URL.createObjectURL(file);
img.onload = function() {
if (img.width > width || img.height > height) {
reject(`上传尺寸最大${initwidth}px * ${initheight}px!`);
} else {
resolve(true);
}
};
});
};
const beforeUpload = (file) => {
const isJpgOrPng =
file.type === "image/jpeg" ||
file.type === "image/png" ||
file.type === "image/bmp";
if (!isJpgOrPng) {
console.log('你必须上传 JPG/PNG 文件!');
return false;
}
const isLt3M = file.size / 1024 / 1024 < 3;
if (!isLt3M) {
console.log('图像必须小于3MB!');
return false;
}
return getFileWidthAndHeight(file, 500, 500);
};
</script>
</html>