将ReadableStream用作HTML <img/>源

时间:2016-11-05 21:28:30

标签: javascript jquery html

我使用fetch从服务器动态加载图像。如何在HTML中将返回的ReadableStream用作图像源?在下面的代码示例中,data.body是一个ReadableStream,现在如何在网页中设置图像源?有没有办法使用管道来成像源?

imageService.js

getImage(key) {
    if(key != null) {
        return this._downloadImageMap().then((imageMap) => {
            let uri = imageMap[key];
            if(uri != null) {
                return this.client.fetch(uri).then((data) => {
                    return data.body;
                });
            } else {
                throw new Error('image not found');
            }
        });
    } else {
        return Promise.reject(new Error('no key specified'));
    }
}

示例所需用法(不起作用):

this.imageService.getImage(this.skill).then((imgStream) => {
        $('#theImage').attr('src', 'data:image/png;base64,' + imgStream);
});

2 个答案:

答案 0 :(得分:2)

在调用fetch(不需要)之后我不会返回imageData的方式略有不同

另外,我没有使用FileReader,这对内存和放大器来说更糟糕。 CPU

&#13;
&#13;
getSkillImage(key) {
  return key 
  ? this._downloadImageMap().then(imageMap => {
    let {path} = imageMap[key]
    return path 
      ? this.client.fetch(path).then(response => response.blob())
      : Promise.reject(new Error('image not found'))
  })
  : Promise.reject(new Error('no key specified'))
}

this.imageService.getSkillImage(this.skill).then(imageData => {
  this.imageLoaded = true
  let src = URL.createObjectURL(imageData)
  $('#' + this.skill + '> img').attr('src', src)
})
&#13;
&#13;
&#13;

答案 1 :(得分:1)

注意此方法有效,但下面的@Endless回答要好得多,因为您不必使用FileReader。

对于那些寻找同样答案的人,我用以下解决方案解决了这个问题:

getSkillImage(key) {
    if(key != null) {
        return this._downloadImageMap().then((imageMap) => {
            let uri = imageMap[key].path;
            if(uri != null) {
                return this.client.fetch(uri).then((response) => response.blob()).then((imageData) => {
                    return imageData;
                });
            } else {
                throw new Error('image not found');
            }
        });
    } else {
        return Promise.reject(new Error('no key specified'));
    }
}

现在将图像添加到HTML DOM中:

this.imageService.getSkillImage(this.skill).then((imageData) => {
        this.imageLoaded = true;
        let reader = new FileReader();
        reader.onload = (event) => {
            let base64String = event.target.result;
            $('#' + this.skill + '> img').attr('src', base64String);
        };
        reader.readAsDataURL(imageData);
    });