1. 程式人生 > >js將圖片轉為base64編碼 && js將base64編碼圖片轉為Blob格式

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' }); }