Created
April 6, 2024 20:59
-
-
Save nyancodeid/c81d7bc5bdcc77626fa4996682d92e64 to your computer and use it in GitHub Desktop.
Browser: Turn Uint8Array into ImageData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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