Given a typed array such as:
const myBuffer = new Uint8Array([255,0,0,255])
How could I obtain a base64 encoded an image, to be put in the DOM?
<img src={ whatToDoHere(myBuffer) }/>
I'd like to see a 1px x 1px red image.
I'm reading a WebGL render target using gl.readPixels(). My mind melted from reading about a dozen different questions regarding this, and none of them solved my issue.
If I render directly to the canvas, I can use toDataURL on the DOM element (canvas) and get what I need. I'd like to do it from a target though, not the drawing buffer.
This is a bit off topic. Here a solution without WebGL or the Canvas. This is very simple using a Blob:
// Small red dot image
const content = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 5, 0, 0, 0, 5, 8, 6, 0, 0, 0, 141, 111, 38, 229, 0, 0, 0, 28, 73, 68, 65, 84, 8, 215, 99, 248, 255, 255, 63, 195, 127, 6, 32, 5, 195, 32, 18, 132, 208, 49, 241, 130, 88, 205, 4, 0, 14, 245, 53, 203, 209, 142, 14, 31, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130]);
document.getElementById('my-img').src = URL.createObjectURL(
new Blob([content.buffer], { type: 'image/png' } /* (1) */)
);
Should display a small red dot: <img id="my-img">
(1) It also works without specifying the MIME type.
A solution would be to directly generate a data URL from webgl's canvas using canvas.toDataURL, which also supports image compression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With