1

I need to convert a png with color into a png that is only black and white. I'm currently processing images Sharp.js. But I haven't been able to find a way to generate a monochromatic image.

I found a greyscale option.

const sharp = require('sharp');

sharp('color-image.png')
    .toGreyscale()
    .toFile('b-w-image.png')
    .then(() => {
        console.log('Huzzah!')
});

But this doesn't work for my needs. I'm looking for a pure black and white image with no shades of grey.

I haven't found anything in the documentation that allows you to specify the level of greyscale to allow for only a B/W image.

Is there a method available that converts the image into pure black and white?

Progman
  • 16,827
  • 6
  • 33
  • 48
Ben Downey
  • 2,575
  • 4
  • 37
  • 57

1 Answers1

1

This will get you an image with two colors. Increase the contrast using the linear option.

const sharp = require('sharp');

sharp('ben.png')
    .greyscale() // make it greyscale
    .linear(1.5, 0) // increase the contrast
    .png({colors:2}) // reduce image to two colors
    .toFile('b-w-image.png')
    .then(() => {
        console.log('Huzzah!')
});
Stephen Taylor
  • 798
  • 7
  • 19