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.
>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)
Note: sandbox is a bit laggy, if image is not shown – refresh the built-in browser