Convert image to 2 colors in Java

I would like to convert an image to 2-color, black and white using Java. I use 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 change this to convert to black and white.

+6
source share
1 answer

Based on another answer (which got shades of gray):

 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 this with ColorConvertOp because there is no binary color space.

+8
source

Source: https://habr.com/ru/post/911037/


All Articles