6

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.

Steve McLeod
  • 51,737
  • 47
  • 128
  • 184

1 Answers1

8

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.

Steve McLeod
  • 51,737
  • 47
  • 128
  • 184
Viruzzo
  • 3,025
  • 13
  • 13