Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an image to 2-colour in Java

I would like to convert an image to 2-color, black and white using Java. I'm using the following code to convert to grayscale:

    ColorConvertOp op = new ColorConvertOp(
             ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
    BufferedImage grayImage = op.filter(image, null);

But I'm not sure how to modify this to convert to just black and white.

like image 778
Steve McLeod Avatar asked Mar 18 '12 15:03

Steve McLeod


Video Answer


1 Answers

Based on another answer (that produced grayscale):

public static BufferedImage toBinaryImage(final BufferedImage image) {
    final BufferedImage blackAndWhiteImage = new BufferedImage(
            image.getWidth(null), 
            image.getHeight(null), 
            BufferedImage.TYPE_BYTE_BINARY);
    final Graphics2D g = (Graphics2D) blackAndWhiteImage.getGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return blackAndWhiteImage;
}

You cannot do it with ColorConvertOp because there is not binary colorspace.

like image 132
Viruzzo Avatar answered Oct 13 '22 18:10

Viruzzo