js将图片转为base64编码 && js将base64编码图片转为Blob格式

将图片转为base64编码格式

function convertImgToBase64(url, callback, outputFormat){
     
  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(outputFormat || 'image/png');
     callback.call(this, dataURL);
     canvas = null; 
  };
  img.src = url;
}

将图片base64编码格式转为blob格式

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

你可能感兴趣的:(Javascript,javascript)