简体   繁体   English

如何 base64 在 JS 中编码二进制图像以供浏览器显示

[英]How to base64 encode binary image in JS for browser showing

We have a problem with showing in browser (actually Chrome) binary images receiving from REST backend API.我们在浏览器(实际上是 Chrome)中显示从 REST 后端 API 接收的二进制图像时遇到问题。 The backend REST endpoint defined in Java like this在 Java 中定义的后端 REST 端点就像这样

@GetMapping(path = "/images/{imageId:\\d+}/data", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody byte[] getImageData(@PathVariable long imageId) {
    return ... skipped ...
}

On the frontend we do these steps:在前端,我们执行以下步骤:

  1. request image data via fetch JS method call通过fetch JS 方法调用请求图像数据
    async function getImage(id) {
        return await fetch(`${URL}/images/${id}/data`, {
            method: 'GET',
            headers: new Headers(HEADERS)
        }).then(response => {
             return response.text();
        });
    }
  1. thus on frontend we have raw binary image data in this format (so far so good - it's really JPEG binary data).因此在前端我们有这种格式的原始二进制图像数据(到目前为止一切都很好 - 它实际上是 JPEG 二进制数据)。 Attached the source JPEG附上源JPEG

https://www.dropbox.com/s/8mh6xz881by5lu1/0gCrmsLkgik.jpg?dl=0 https://www.dropbox.com/s/8mh6xz881by5lu1/0gCrmsLkgik.jpg?dl=0

  1. then we call this code to receive base64 encoded image然后我们调用这个代码来接收 base64 编码图像
    let reader = new FileReader();
        reader.addEventListener('loadend', event => {
        console.log(event.srcElement.result)
    });

    reader.readAsDataURL(new Blob([data]));
  1. as a result we have something looks like base64 encoded data结果我们有一些看起来像 base64 编码的数据

https://www.dropbox.com/s/uvx042j2dgizkr9/base64.txt?dl=0 https://www.dropbox.com/s/uvx042j2dgizkr9/base64.txt?dl=0

  1. we tried to put base64 encoded data into <img> element without any success:(我们试图将 base64 编码数据放入<img>元素中,但没有成功:(

So the question is how to receive on frontend correct base64 images for browser showing?所以问题是如何在前端接收正确的 base64 图像以供浏览器显示? What we do wrong?我们做错了什么?

Here's some working code, based on this example and the @somethinghere's comment above.这是一些工作代码,基于此示例和上面的@somethinghere 评论。 Pay attention to how the response is handled in getImage :请注意在getImage中如何处理response

 function getImage(id) { return fetch(`https://placekitten.com/200/140`, { method: 'GET', }).then(response => { return response.blob(); // <- important }); } async function loadAndDisplay() { let blob = await getImage(); let imageUrl = URL.createObjectURL(blob); let img = document.createElement('img'); img.src = imageUrl; document.body.appendChild(img) } loadAndDisplay()

That said, a much simpler option would be just to insert a tag like <img src=/images/id/data> and leave all loading/displaying to the browser.也就是说,一个更简单的选择是插入一个标签,如<img src=/images/id/data>并将所有加载/显示留给浏览器。 In this case your backend has to provide the correct content-type though.在这种情况下,您的后端必须提供正确的内容类型。

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

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