How to convert an array of bytes into an image that can be drawn onto a canvas?

440 Views Asked by At

I'm using node-canvas to do some image manipulation (in this example to convert the image to a grayscale version, just to keep the example simple). I have no issues getting the raw data, but I'm having trouble working out how to convert the derived array of data back into something that the canvas context can draw.

import { writeFile } from "fs/promises";
import { loadImage } from "canvas"

import { OUTPUT, WIDTH, HEIGHT } from "../config";

const fadeToGray = ctx => {
  const src = ctx.getImageData(0, 0, WIDTH, HEIGHT).data;
  const dst = new Uint32Array(src.length >> 2);
  
  for (let i = 0; i < src.length; i += 2) {
    dst[i >> 2] = (src[i] * 4899 + src[++i] * 9617 + src[++i] * 1868 + 8192) >> 14;
  }
  
  // I'm stuck here!
  const image = CONVERT_BYTES_TO_IMAGE(dst);

  ctx.drawImage(image, 0, 0, WIDTH, HEIGHT);
}

const start = async () => {
  const image = await loadImage('input/test.png');
  const canvas = createCanvas(WIDTH, HEIGHT);
  const ctx = canvas.getContext("2d");
  ctx.drawImage(image, 0, 0, WIDTH, HEIGHT);

  fadeToGray(ctx);

  writeFile(`${OUTPUT}/test.png`, canvas.toBuffer("image/png"));
}

start().then(() => {
  console.log('done')
}).catch(err => {
  console.error('dammit', err)
});

I feel like I'm missing something very obvious. How do I convert my array of bytes back into a drawable image?

0

There are 0 best solutions below