Reputation: 52448
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.
Upvotes: 6
Views: 2790
Reputation: 3025
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.
Upvotes: 8