圖片Image轉換爲base64編碼的方法

一、FileReaderjavascript

經過XMLHttpRequest請求圖片Blob數據格式,而後利用FileReader轉換爲dataURLjava

function toDataURL(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
      callback(reader.result);
    }
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}

toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
  console.log('RESULT:', dataUrl)
})

請求能夠利用 WHATWG fetchJs來實現web

const toDataURL = url => fetch(url)
  .then(response => response.blob())
  .then(blob => new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
    reader.onerror = reject
    reader.readAsDataURL(blob)
  }))


toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0').then(dataUrl => {
    console.log('RESULT:', dataUrl)
})

優缺點:chrome

  • 某些瀏覽器缺少支持
  • 更好的文件壓縮
  • 適用其餘文件類型

查看支持:canvas

二、Canvas瀏覽器

新建圖片,在畫布上實現,而後將canvas對象轉變爲一個dataURL緩存

function toDataURL(src, callback, outputFormat) {
  var img = new Image();
  img.crossOrigin = 'Anonymous'; // 容許image請求的圖片應用到canvas,就像他們在同一個域
  img.onload = function() {
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var dataURL;
    canvas.height = this.naturalHeight;
    canvas.width = this.naturalWidth;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL(outputFormat);
    callback(dataURL);
  };
  img.src = src;
  if (img.complete || img.complete === undefined) { // 確保對緩存的圖片也觸發img.onload事件
    img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    img.src = src;
  }
}

toDataURL(
  'https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0',
  function(dataUrl) {
    console.log('RESULT:', dataUrl)
  }
)

支持的inputFormat:svg

  • image/pngimage/jpegimage/jpgimage/gifimage/bmpimage/tiffimage/x-iconimage/svg+xmlimage/webpimage/xxx

支持的outputFormat:fetch

  • image/pngimage/jpegimage/webp(chrome)

查看支持:this

三、從當前文件系統讀取,input讀取文件後,利用FileReader進行轉換

function encodeImageFileAsURL(element) {
  var file = element.files[0];
  var reader = new FileReader();
  reader.onloadend = function() {
    console.log('RESULT', reader.result)
  }
  reader.readAsDataURL(file);
}
<input type="file" onchange="encodeImageFileAsURL(this)" />
相關文章
相關標籤/搜索