Last active
September 23, 2017 19:18
-
-
Save samuelmaddock/9c48905c2e53e4c5ecb4429ab8c9d132 to your computer and use it in GitHub Desktop.
Converts RGBA data to a URL using an HTML canvas element
This file contains 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
export const rgba2url = async ( | |
rgba: Uint8Array, | |
width: number, | |
height: number | |
): Promise<string | void> => { | |
let canvas = document.createElement('canvas'); | |
canvas.width = width; | |
canvas.height = height; | |
let ctx = canvas.getContext('2d'); | |
if (!ctx) { | |
return; | |
} | |
let imgData = ctx.createImageData(width, height); | |
for (let i = 0; i < imgData.data.length; i += 4) { | |
imgData.data[i + 0] = rgba[i]; | |
imgData.data[i + 1] = rgba[i + 1]; | |
imgData.data[i + 2] = rgba[i + 2]; | |
imgData.data[i + 3] = rgba[i + 3]; | |
} | |
ctx.putImageData(imgData, 0, 0); | |
const blobUrl = await new Promise<string>(resolve => { | |
canvas.toBlob(blob => { | |
let url = URL.createObjectURL(blob); | |
resolve(url); | |
}); | |
}); | |
return blobUrl; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment