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 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.
Im not sure if there is a simplest way to convert bytes array to base64 string, but it works.
const byteArray = Object.values(array.encodedImage);
const base64String = Buffer.from(byteArray).toString("base64");
document.getElementById("app").innerHTML = `
<img src="data:image/png;base64,${base64String}"/>
`;
Notes: (thanks to @ikegami and @evert)
As per MSN
The traversal order, as of modern ECMAScript specification, is well-defined and consistent across implementations. Within each component of the prototype chain, all non-negative integer keys (those that can be array indices) will be traversed first in ascending order by value, then other string keys in ascending chronological order of property creation.
Polyfills and shims: Tested core-js v1.0.0 polyfill and object.values v1.0.0 shim, both do preserve the required order.
Note: sandbox is a bit laggy, if image is not shown - refresh the built-in browser
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="">