Bootstrap

图片转file\blob文件、图片转base64

//图片url转blob文件
var imageUrlTransFiles = function (imgUrl, call) {
	var that = this,
		image = new Image();

	if(imgUrl.indexOf('?') !== -1){
        imgUrl = imgUrl + '&v=' + Math.random();
    }else{
        imgUrl = imgUrl + '?v=' + Math.random();
    }
	image.src = imgUrl;
	image.setAttribute('crossOrigin', 'anonymous'); //跨域
	image.onload = function () {
		var dataURL = getBase64Image(image); //获取base64的图片地址

        if(dataURL.isBase64){
            try {
                var myFile = '',
                    arr = dataURL.url.split(','), //把图片地址分割
                    mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]), //转blob类型
                    n = bstr.length,
                    u8arr = new Uint8Array(n);

                //处理数据,准备生成file文件流
                for (var i = 0; i < n; ++i) {
                    u8arr[i] = bstr.charCodeAt(i);
                }
                myFile = new Blob([u8arr], {type: mime}); //把处理好的base64的图片地址转成Blob文件流,new File不支持ie,所以需要用Blob

                typeof call === 'function' && call(myFile);
            }catch(e){
                typeof call === 'function' && call();
            }
        }else{
            typeof call === 'function' && call();
        }
	};

	image.error = function(){
		typeof call === 'function' && call();
	};
};

//获取base64流图片地址,把img节点丢进canvas后转成base64图片流地址
var getBase64Image = function(img) {
	var canvas = document.createElement('canvas'),
        imgURLObj = {
	        url: img.src,
            isBase64: false
        };

    try {
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase();
        imgURLObj.url = canvas.toDataURL('image/' + ext);
        imgURLObj.isBase64 = true;
    }catch(e){}
	return imgURLObj;
};
;