简体   繁体   中英

Convert binary to blob url

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" />

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, eg jpeg, png, etc.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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