1、HTML
<div>
<input onchange="imageChange(event)" type="file" accept="image/*" capture="camera"/>
</div>
<div>
<img id="myimage"/>
</div>
2、CSS
#myimage{
max-width: 1000px;
}
3、Javascript
function imageChange(evt) {
const _this = this;
const compressConfig = {
quality: 0.92, //为了保持图像质量,压缩值设置为 0.92
width: 1000 //图像宽度调整为1000,高度自动适配
};
var file = evt.target.files[0];
var type = file.type.split('/')[0];
if (type === 'image') {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function () {
var dataURL = reader.result;
//压缩图片
_this.compressImg(dataURL, compressConfig, file);
};
} else {
alert ('uploaded non image ');
}
}
function compressImg(dataURL, compressConfig, file) {
var img = new Image();
img.src = dataURL;
img.onload = function () {
var that = this;
//默认图像压缩参数
var quality = 0.5;
var w = that.width;
var h = that.height;
var scale = w / h;
//实际压缩参数
w = compressConfig.width || w;
h = compressConfig.height || (w / scale);
if (compressConfig.quality && compressConfig.quality > 0 && compressConfig.quality <= 1) {
quality = compressConfig.quality;
}
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var anw = document.createAttribute('width');
anw.nodeValue = w;
var anh = document.createAttribute('height');
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
//base64为压缩后的数据
var base64 = canvas.toDataURL('image/jpeg', quality);
//console.log(base64);
document.querySelector('#myimage').src=base64;
}
}
参考资料:
Using canvas image compression, size adjustment