javascripttypescriptdeno

Get width/height of pixels array in Uint8ClampedArray


I am using TypeScript on Deno. I am trying to use blurhash.

This is my code:

const response = await fetch(url);
if (!response.body) {
throw new Error("Body null");
}

const clamped = new Uint8ClampedArray(await response.arrayBuffer());
var blurhash: string = encode(clamped, width, height, 4, 4,);

where width and height is known beforehand. But I get this error:

Width and height must match the pixels array

I read this issue and it seems like the alpha channel is missing or something. The problem is, that all solutions are fixing it by using sharp with ensureAlpha(). But sharp is not running on Deno, so I can't use it.

Does anyone know how I could fix this?


Solution

  • The blurhash library you are using expects an Uint8Array of raw bitmap pixels in the format [R, G, B, A]. Here you are feeding it the whole png file, with its headers, its metadata and the pixel data compressed in it.

    You will need to actually read that image file in order to gain access to this raw bitmap data. There are various libraries that do that, I'll let you pick one, but unfortunately deno ones require CSP rules that we don't have here in StackSnippet so I can 't make a live demo.

    import * as blurhash from "https://esm.sh/blurhash";
    // Or any other library
    import decode from "https://deno.land/x/wasm_image_decoder@v0.0.7/mod.js";
    
    const response = await fetch(url);
    if (!response.body) {
      throw new Error("Body null");
    }
    const fileBuffer = await response.arrayBuffer();
    const { data, width, height } = await decode(fileBuffer);
    const hash = encode(data, width, height, 4, 4,);
    console.log(hash);