【问题标题】:Can i apoint the src img attribute to a blob file or a base64 encoded image?我可以将 src img 属性指向 blob 文件或 base64 编码图像吗?
【发布时间】:2020-01-11 07:34:35
【问题描述】:

我想知道是否可以通过某种方式获取 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();

【问题讨论】:

    标签: javascript image base64 blob angular7


    【解决方案1】:

    您可以将图像 src 设置为 Base64 dataURI,但不能设置为 blob。

    如果不违反任何 cors 政策,您可以将图像作为 blob 检索,然后将其转换为 dataURI。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多