I have a ReadableStream<Uint8Array>
and need to convert it to Uint8ClampedArray
in TypeScript Deno.
I tried some solutions I could find. Like this:
const getImageData = image => {
const canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
const context = canvas.getContext("2d");
if (context != null) {
context.drawImage(image, 0, 0);
return context.getImageData(0, 0, image.width, image.height);
}
};
But it already fails because document
can't be found.
Is there a straight forward casting/converting from ReadableStream<Uint8Array>
to Uint8ClampedArray
?
My ReadableStream comes from this:
const image = (await fetch(url)).body!;
I want to do all this, to create a blurhash
. But when just using the Uint8Array
I get ValidationError: Width and height must match the pixels array
If you have a
ReadableStream
and don't know the byte length of the stream, then you can collect the bytes and concatenate them in order to construct an instance ofUint8ClampedArray
:Code in TypeScript Playground
Use it with your example code like this:
However, if you're starting with an instance of
Response
then you can use its async methodarrayBuffer()
to construct the clamped array more simply: