下面这段代码是我爱模板网为解决头像过大,从网上找的压缩base64图片的方法:compressPic('参数一:base64地址','参数二:缩小比例,值越大,图片越小','参数三:回调函数callback'),得到的结果在callback中使用,callback有两个默认参数,第一个是压缩后的blob图片对象,第二个是压缩后的图片base64地址(这里我把它定义成了对象的方法):
compressPic:function(base64, bili, callback){
var that = this;
var _img = new Image();
_img.src = base64;
_img.onload = function() {
var _canvas = document.createElement("canvas");
var w = this.width / bili;
var h = this.height / bili;
_canvas.setAttribute("width", w);
_canvas.setAttribute("height", h);
_canvas.getContext("2d").drawImage(this, 0, 0, w, h);
var base64 = _canvas.toDataURL("image/jpeg");
// 当canvas对象的原型中没有toBlob方法的时候,手动添加该方法
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
value: function (callback, type, quality) {
var binStr = atob(this.toDataURL(type, quality).split(',')[1]),
len = binStr.length,
arr = new Uint8Array(len);
for (var i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i);
}
callback(new Blob([arr], {type: type || 'image/png'}));
}
});
}else{
_canvas.toBlob(function(blob) {
if(blob.size > 1024*1024){
that.compressPic(base64, bili, callback);
}else{
callback(blob, base64);
}
}, "image/jpeg");
}
}
}
此外,本方法传递的base64需要加上开头,如:‘data:image/jpeg;base64,’,得到的结果也有头,如果不需要的话可以用下面的代码去除:
base64url.replace(/^data:image\/(jpeg|png|gif|jgp);base64,/,'')