1

I have a binary data of a image like 137, 80, 78, 71, 13, 10, 26, 10, 0 as String. I want to display it in html as blob url. How do i convert the binary to blob url. I have tries doing these but i am not getting the image.

var binary = "137, 80, 78, 71, 13, 10, 26, 10, 0";
var blob = new Blob([binary], { type: 'image/png' });
var blobUrl = URL.createObjectURL(blob);

console.log(blobUrl);
document.getElementById("image").src = blobUrl;
<img id="image" />
JO3-W3B-D3V
  • 2,124
  • 11
  • 30
Manas Sanas
  • 342
  • 9
  • 18
  • Does this answer your question? [Using JavaScript to display a Blob](https://stackoverflow.com/questions/7650587/using-javascript-to-display-a-blob) – Justinas Jul 09 '20 at 14:07

2 Answers2

1

You have to:

  1. convert your string to an array of integers,
  2. convert that array to a binary string,
  3. convert that to base64 and
  4. inject that into the src attribute of your <img>.
var numbers = binary.trim().split(/\s*,\s*/g).map(x => x/1);
var binstr = String.fromCharCode(...numbers);
var b64str = btoa(binstr);
var src = 'data:image/jpeg;base64,' + b64str;
document.getElementById("image").src = src;

Bear in mind that you have to use the proper image type, e.g. jpeg, png, etc.

jotaelesalinas
  • 1,387
  • 1
  • 11
  • 24
0

When you want to show the image, you have to do something like this:

var binary = "137, 80, 78, 71, 13, 10, 26, 10, 0";
document.getElementById("image").src = 'data:image/jpeg;base64,' + btoa(binary)

But I am not sure whether your binary is correct or not.