简体   繁体   English

Javascript:临时存储和显示从后端接收到的图像作为二进制数据?

[英]Javascript: Temporarily store and display image received from backend as binary data?

I am currently trying to display an image, which I receive from a backend server in a particular way/format, on the screen of the browser.我目前正在尝试在浏览器的屏幕上显示我以特定方式/格式从后端服务器接收到的图像。

My problem is acutally closely related to this issue, for which no real answer exists.我的问题与这个问题密切相关,没有真正的答案。

Here is a screenshot displaying what the backend server's response looks like:这是显示后端服务器响应的屏幕截图:

在此处输入图像描述

payload.data contains the data of the image, which is a green cloud (also attached at the end of this post for reference). payload.data包含图像的数据,它是一个绿色的云(也附在本文末尾以供参考)。

My first, probably very stupid, question would be: What kind of format/encoding is that?我的第一个可能非常愚蠢的问题是:那是什么格式/编码?

Anyway, here is what I then further tried to process the data:无论如何,这是我随后进一步尝试处理数据的内容:

        const blob = new Blob([action.payload.data], { //contains the data
            type: action.payload.headers["content-type"] // 'image/png'
        })
        console.log("blob: ", blob);
        const url = URL.createObjectURL(blob);
        console.log("url : ", url)

As a result, the blob is sucessfully created, as well as the url.结果,成功创建了 blob 以及 url。 However, when I open that link, no image gets displayed.但是,当我打开该链接时,不会显示任何图像。

I am stuck here and would appreaciate any kind of helpful hint pointing out where I am doing a mistake here.我被困在这里,并且会欣赏任何有用的提示,指出我在这里做错了。

Thanks very much for your support in advance.非常感谢您提前的支持。

PS: As promised, here is the actual png image: PS:正如所承诺的,这是实际的 png 图像: 在此处输入图像描述

It seems like your data attribute is still in binary format.看起来您的data属性仍然是二进制格式。 You need to convert the hex into base64 in order to display the image.您需要将十六进制转换为 base64 才能显示图像。 First, if the server you're fetching the image form is yours, I would recommend encoding the image on the server before sending it to the client.首先,如果您要获取图像表单的服务器是您的,我建议在将图像发送到客户端之前在服务器上对图像进行编码。 If the server is not yours and you can't change the data that is being returned, try something like this:如果服务器不是您的,并且您无法更改返回的数据,请尝试以下操作:

function hexToBase64(str) {
    return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}

And then use it like this:然后像这样使用它:

const img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + hexToBase64('your-binary-data');
document.body.appendChild(img);

reference: How to display binary data as image - extjs 4参考: 如何将二进制数据显示为图像 - extjs 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM