Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting JSON containing list of 0-255 values as base64 image using Javascript

An undocumented WebAssembly UI component I use is supposed to return JPEG-encoded image in JSON.

Here is the (truncated) result:

{
   "encodedImage":{
      "0":255,
      "1":216,
      ...
      "13151":216,
      "13152":255,
      "13153":217
   }
}

I am struggling to understand how to convert this data structure (unknown to me) to a valid JPEG base64-encoded image.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried the following on Repl.it, but the output is not processable in a JPEG decoder, so wrong way:

console.log(btoa(JSON.stringify(array.encodedImage)));

Any idea on how to convert this list of values to a valid JPEG base64-encoded image ?

EDIT: The purpose is to display the image it in HTML, hence the base-64 encoding required.

>Solution :

Im not sure if there is a simplest way to convert bytes array to base64 string, but it works.

const byteArray = [];
for (const [key, value] of Object.entries(array.encodedImage)) {
  byteArray[parseInt(key, 10)] = value;
}
const base64String = btoa(String.fromCharCode(...new Uint8Array(byteArray)));

document.getElementById("app").innerHTML = `
  <img src="data:image/png;base64,${base64String}"/>
`;

(Updated to preserve order of items, thanks to @ikegami)

Edit stoic-ishizaka-hdv2pb

Note: sandbox is a bit laggy, if image is not shown – refresh the built-in browser

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading