base64编码数据与图片格式互相转换

1、base64转换成图片

function base64DataToBlob(dataUrl){  
   //去掉url的头,并转换为byte
    var bytes = window.atob(urlData.split(',')[1]);        
    //处理异常,将ascii码小于0的转换为大于0  
    var ab = new ArrayBuffer(bytes.length);  
    var ia = new Uint8Array(ab);  
    for (var i = 0; i < bytes.length; i++) {  
        ia[i] = bytes.charCodeAt(i);  
    }  
    return new Blob( [ab] , {type : 'image/png'});  
}  

2、图片转换成base64

function ImgToBase64(url, fn) {
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var img = new Image;
    img.crossOrigin = 'Anonymous';  //处理跨域图片   
    img.src = url;     
    img.onload = function() {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL( 'image/png');
        fn.call(this, dataURL); 
        canvas = null;
    };
}  

你可能感兴趣的:(base64编码数据与图片格式互相转换)