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

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/xiaobing_hope/article/details/78835671

将图片转为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' });
}
展开阅读全文

没有更多推荐了,返回首页