gpt4 book ai didi

javascript - 显示来自 http get 请求的 PNG

转载 作者:可可西里 更新时间:2023-11-01 16:29:40 28 4
gpt4 key购买 nike

我正在使用 angular 4,我正在使用一个返回带有 content-type : img/png

图像的 api

http 方法:

return this.http.get('URL', this.options)
.map((res: Response) => res.text());
// can be also : res.arrayBuffer() // res.blob()

http get 响应(在文本和 ARC 中)是这样的:

�PNG  IHDR��"͹�W�W��zؽ�|+q%�   ��Y������M缥{��U��H�ݏ)L�L�~�6/'6Q׌�}���:��l'���� �R�L�&�~Lw?�

我尝试了不同的方法来转换和显示它:

  • 将响应作为 blob 并使用 :

    进行转换
     new Uint8Array(response)
  • 将图像获取为 arrayBuffer 然后使用 :

    转换它
      arrayBufferToBase64(buffer) {
    let binary = '';
    let bytes = new Uint8Array(buffer);
    let len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
    }

他们两个都不适合我,图像不显示。

我的问题是,响应的实际格式是什么(blob、arraybuffer 或文本)以及如何显示它?

最佳答案

您可以使用 fetch API 实现这一点。

让我们首先将响应作为 blob 返回。然后您可以使用 URL.createObjectURL() 创建一个文件对象。

fetch(URL)
.then(res=>{return res.blob()})
.then(blob=>{
var img = URL.createObjectURL(blob);
// Do whatever with the img
document.getElementById('img').setAttribute('src', img);
})

Demo

关于javascript - 显示来自 http get 请求的 PNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47001306/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com