How to replace all colours except black in image Node.JS

1.8k views Asked by At

I am trying to create a silhouette of an image. I have already made the background black but I am having trouble converting all other colours to grey.

My code so far:

import sharp from "sharp";
import jimp from "jimp";

sharp("input.png")
  .flatten()
  .toFile("output.jpg")
  .then(async (data) => {
    const image = await jimp.read("output.jpg");

    image.scan(0, 0, image.bitmap.width, image.bitmap.height, (x, y, idx) => {
      if (image.bitmap.data[idx] >= 2) {
        image.bitmap.data[idx] = 86;
        image.bitmap.data[idx + 1] = 101;
        image.bitmap.data[idx + 2] = 115;
        image.bitmap.data[idx + 3] = image.bitmap.data[idx + 3];
      }
    });

    image.write("output.jpg");
  });

This code outputs: result

The input image was: enter image description here

I have looked a packages like replace-color but those seem to be aimed at replacing a single colour, not all but one. Any help is much appreciated

1

There are 1 answers

0
AudioBubble On BEST ANSWER

Problem was that I was changing the format from png to jpg. Keeping it as png fixes the problem