簡體   English   中英

我可以將src img屬性指定為Blob文件還是以base64編碼的圖像?

[英]Can i apoint the src img attribute to a blob file or a base64 encoded image?

我想知道是否能以某種方式獲取url的圖像內容並將其轉換為base64或blob文件並將其附加到src屬性?

如果可能的話,我該怎么做呢? 我試圖做這樣的事情,它不起作用

    const fileReader = new FileReader();
    let userAvatar: string;
    this.avatarSubject = new BehaviorSubject(this.userService.getAvatar(this.channelId));
    this.avatarSubject.subscribe(res => {
      userAvatar = res;
      const binaryImg = atob(userAvatar);
      const length = binaryImg.length;
      const buffer = new ArrayBuffer(length);
      const uint = new Uint8Array(buffer);
      const blob = new Blob([uint], {type: 'image/jpeg'});
      fileReader.readAsDataURL(blob);
    }).unsubscribe();

您可以將圖片src設置為Base64 dataURI,而不是blob。

您可以將圖片檢索為Blob,然后將其轉換為dataURI(如果它不違反任何cors策略)。

(async ()=>{
  var url = 'https://imgur.com/gallery/rh5O7wN';
  var blob = await urlToBlob(url);
  var datauri = await blobToDataURI(blob);
  document.getElementById('img').src = datauri;
})();

function urlToBlob(url) {
  return new Promise(done => {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = 'arraybuffer';
    xhr.addEventListener('load', function() {
      if (xhr.status === 200) done(new Blob([xhr.response]));
    })
    xhr.send();
  });
}

function blobToDataURI(blob) {
  return new Promise(done => {
    var a = new FileReader();
    a.onload = e => done(e.target.result);
    a.readAsDataURL(blob);
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM