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

Time:08-21

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.

I have tried the following on Edit stoic-ishizaka-hdv2pb

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

CodePudding user response:

You don't need the conversion to base64, this is expensive and makes your HTML huge.

My guess is that your input array is a UInt8Array, so to turn it back into that so we can manipulate it:

const byteArray = UInt8Array.from(Object.values(input.encodedImage));

Next, turn it into a Blob:

const blob = new Blob(byteArray);

And finally get the object URI

const url = URL.createObjectURL(blob);

This URL you can put in your <img src="">

  • Related