<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="file" onchange="loadImg(this)">
<canvas style="width: 200px; height: 200px;"></canvas>
<img src="" alt="" id="imgs">
<script>
// 上传图片
function loadImg(me) {
let img = document.querySelector('img');
let cvs = document.querySelector('canvas');
let file = me.files[0]; // 获取到文件对象
// 上传的图片大于 500KB 时才压缩
if (file && (file.size / 1024 > 150)) {
let reader = new FileReader();
reader.readAsDataURL(file); // 转成 base64 编码
reader.onload = function (e) {
let naturalBase64 = e.target.result; // 获取 base64 编码,这是原图的
img.src = naturalBase64;
img.onload = function () {
let ratio = img.naturalWidth / img.naturalHeight; // 获取原图比例,为了等比压缩
cvs.width = 400;
cvs.height = cvs.width / ratio;
let ctx = cvs.getContext('2d');
ctx.drawImage(img, 0, 0, cvs.width, cvs.height); // 画在 canvas 上
// 压缩后新图的 base64
let zipBase64 = cvs.toDataURL('image/jpeg',0.7);//0.7代表图片质量
console.log(zipBase64)
}
}
}
}
</script>
</body>
</html>
html上传图片后压缩图片,图片预览,获取压缩后的Base64
最新推荐文章于 2023-02-28 15:00:14 发布