0

I am trying to convert the data retrieved from an API to a Blob to be able to display it as an image on my page.
In the response, I get the data string which in the browser console looks like shown below. I assume that it is just a binary data of a file (it looks like it to me).

Binary data string in the console

I use this code to convert the string to the Blob:

const convertBinaryToBlob = (binary: string, contentType: string): Blob => {
  const uInt8Array = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) {
    uInt8Array[i] = binary.charCodeAt(i);
  }
  return new Blob([uInt8Array], { type: contentType });
};

It gets generated fine, as well as the Blob object URL, so I am able to put it as the src of an image. The problem is that the image cannot be displayed by the browser because it contains some errors.
What's the issue in here? How am I able to get it working?

When I test it using curl, I use this command:

curl -X 'GET' 'http://localhost:8000/images/file/6' -H 'accept: */*' --output img.png

The output file is working without any problem. Response headers from the curl:

HTTP/1.1 200 OK
date: Tue, 25 Jan 2022 20:05:30 GMT
server: uvicorn
content-type: image/png
content-length: 3099363
last-modified: Sun, 23 Jan 2022 18:12:08 GMT
etag: 38e1bb48826eab759ab7220bc805124b
szelbi
  • 67
  • 4
  • 14
  • I've used [this as a temporary solution](https://stackoverflow.com/a/70564656/5905695). I am returning base64 directly from the API. But I am still looking for a solution to the problem described. – szelbi Jan 27 '22 at 17:28

1 Answers1

0

A blob isn't a valid image source. You have to convert the binary data to base64 so you can pass it as an image source.

Replace binaryString with your binary data.

const encodeBase64 = (data) => {
    return Buffer.from(data).toString('base64');
}

var base64EncodedStr = encodeBase64(decodeURI(encodeURIComponent(binaryString)));
var src = "data:image/png;base64," + base64EncodedStr ;

Set your image source equal to the src variable.

Also png could be another image format.

Code composed from this post

Casper Kuethe
  • 1,070
  • 8
  • 13
  • I've used the code provided by you, but unfortunately, it still shows that the file contains errors. Also, as the VS Code has shown me that methods like `btoa` and `unescape` are deprecated, I've found [this solution](https://stackoverflow.com/a/70733727/5905695) which at the first sight returns the same base64, but it does not work either. – szelbi Jan 25 '22 at 21:54
  • My bad i've updated the deprecated methods. When you tried it yourself did you replace unescape with decodeURI? That should be the function that prevents errors... – Casper Kuethe Jan 25 '22 at 22:02
  • I did not, but the first code you have sent did not work either. Now I've copied the code after your edit and it shows the same error. So I think that it's not the issue. – szelbi Jan 25 '22 at 22:07