Ben Downey
Ben Downey

Reputation: 2665

How to convert png pure black & white (no greyscale) with Sharp.js

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?

Upvotes: 2

Views: 2810

Answers (1)

Stephen Taylor
Stephen Taylor

Reputation: 866

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!')
});

Upvotes: 1

Related Questions