canvas、image src、data url、blob file conversion

//canvas.toDataURL('image/jpeg'), and convert to blob,blob is a File Object. but UC don't support
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) u8arr[n] = bstr.charCodeAt(n);
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
if (window.BlobBuilder) {
var bb = new BlobBuilder();
bb.append([u8arr]);
return bb.getBlob(mime);
} else return new Blob([u8arr], { type: mime });
} //html image src convert to dataUrl
function imageToDataURL(url, callback, mime) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function () {
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL(mime || 'image/jpeg');
callback.call(this, dataURL);
canvas = null;
};
img.src = url;
}
上一篇:maven 聚合工程的创建和打包


下一篇:Android开发中常见的设计模式(四)——策略模式