Skip to content

Instantly share code, notes, and snippets.

@nyancodeid
Created April 6, 2024 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyancodeid/c81d7bc5bdcc77626fa4996682d92e64 to your computer and use it in GitHub Desktop.
Save nyancodeid/c81d7bc5bdcc77626fa4996682d92e64 to your computer and use it in GitHub Desktop.
Browser: Turn Uint8Array into ImageData
function bufferIntoImageData (data: Uint8Array): Promise<ImageData> {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d', {
willReadFrequently: true
});
if (!context) {
throw new Error('Canvas context is not available.');
}
return new Promise((resolve) => {
const blob = new Blob([ data ], { type: 'image/png' });
const image = new Image();
image.onload = () => {
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
resolve(context.getImageData(0, 0, image.width, image.height));
}
image.src = URL.createObjectURL(blob);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment