Transform a blurhash to grayscale

54 views Asked by At

Does anyone have an idea of how we can implement an efficient algorithm (js/ts) that given a blurhash string returns the equivalent (even of reduced quality) but in grayscale?

I need it because I use blurhashes as image holders, but in a part of my application I need to display images in black and white. Thanks in advance


EDIT

I managed to arrive at a code like this. the problem is that the blurhashes seem stretched and deformed compared to the originals

const WIDTH = 30;
const ASPECT_RATIO = validationConfig.media.profilePicture.aspectRatio;
const HEIGHT = Math.floor(WIDTH / ASPECT_RATIO);

export function convertBlurhashToGreyscale(blurhash: string) {

  const pixels = decode(blurhash, WIDTH, HEIGHT);


  for (let i = 0; i < pixels.length; i += 4) {
    const grayValue = Math.round(
      (pixels[i] + pixels[i + 1] + pixels[i + 2]) / 3
    );

    pixels[i] = grayValue;
    pixels[i + 1] = grayValue;
    pixels[i + 2] = grayValue;
    pixels[i + 3] = 255; // Imposta l'opacità a 255
  }

  const newHeight = Math.floor(WIDTH / ASPECT_RATIO);
  return encode(pixels, WIDTH, newHeight, 4, 3);
}
0

There are 0 answers