最近项目有用到用户上传图片功能,但我用我手机拍一张图片大小是3.2MB,这么大的图片上传到网站后台再压缩的话很耗费流量,所以上网找了一个方法在上传的时候将图片压缩质量,后为300KB的大小。记录下
var fileBtn = $("input[type=file]");
fileBtn.on("change", function () {
if (filePathAr.length == 6) {
alert("最多6张图片哦~(●'◡'●)");
return;
}
var index = $(this).val().lastIndexOf("\\");
var sFileName = $(this).val().substr((index + 1));
if (sFileName.length > 0) {
var fil = this.files;
var reader = new FileReader();
reader.readAsDataURL(fil[0]);
reader.onload = function (e) {
dealImage(this.result, { width: 200 }, function (base) {
reads(fil[0]);
document.getElementById('imgGH').setAttribute('src', base)
});
}
}
});
//压缩图片算法
function dealImage(path, obj, callback) {
var img = new Image();
img.src = path;
img.onload = function () {
var that = this;
// 默认按比例压缩
var w = that.width,
h = that.height,
scale = w / h;
// w = obj.width || w;
// h = obj.height || (w / scale);
var quality = 0.3; // 默认图片质量为0.7
//生成canvas
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);
// 图像质量
if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
quality = obj.quality;
}
// quality值越小,所绘制出的图像越模糊
var base64 = canvas.toDataURL('image/jpeg', quality);
// 回调函数返回base64的值
callback(base64);
}
}