备忘
function photoCompress(file, obj, objDiv) {
var read = new FileReader();
read.readAsDataURL(file);
read.onload= function () {
var result = this.result;
canvasDataURL(result , obj, objDiv);
}
};
function canvasDataURL(path, obj, callback) {
var img = new Image();
img.src= path;
img.onload = function () {
var that = this;
// 默认按比例压缩
var wid = that.width/2,
hei = that.height/2,
scale = wid/ hei ;
//如果obj有大小,则用obj的大小,否则用默认的
//我这用的长宽压缩一半
wid = obj.width/2 || wid;
hei = obj.height/2 || (wid / scale);
var quality = 0.5; // 默认图片质量为0.7
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 创建属性节点
var anw = document.createAttribute("width");
anw.nodeValue= wid;
var anh = document.createAttribute("height");
anh.nodeValue= hei;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, wid, hei);
// 图像质量
if (obj.quality&& obj.quality<= 1 && obj.quality> 0) {
quality = obj.quality;
}
// quality值越小,所绘制出的图像越模糊
var base64 = canvas.toDataURL('image/jpeg', quality);
// 回调函数返回base64的值
callback(base64);
}
}
//base64转blob
function convertBase64UrlToBlob(urlData) {
var arr = urlData.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime
});
}
网友评论