How to convert BufferedImage to black and white?

How to convert an existing color BufferedImage to monochrome? I want the image to be completely split between two rgb codes, black and white. Therefore, if there is a border around the image, which is a lighter or darker shade of the background, and the background is converted to white, then I want the border to also be converted to white, etc.

How can i do this?

If you need to save the image / load it from disk, I can do this if necessary.

Edit: Verification code:

package test; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.HashSet; import javax.imageio.ImageIO; public class Test { public static void main(String[] args) { try { BufferedImage img = ImageIO.read(new File("http://i.stack.imgur.com/yhCnH.png") ); BufferedImage gray = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY); Graphics2D g = gray.createGraphics(); g.drawImage(img, 0, 0, null); HashSet<Integer> colors = new HashSet<>(); int color = 0; for (int y = 0; y < gray.getHeight(); y++) { for (int x = 0; x < gray.getWidth(); x++) { color = gray.getRGB(x, y); System.out.println(color); colors.add(color); } } System.out.println(colors.size() ); } catch (Exception e) { e.printStackTrace(); } } } 

Image Used:

image

Using this, I get output 24 as the last output, i.e. 24 colors were found in this image, when there should be 2.

+4
source share
1 answer

The solution was to use BufferedImage.TYPE_BYTE_BINARY as a type, not TYPE_BYTE_GRAY . Using BINARY results in a clean black and white copy of the created image without colors other than b and w. Not very pretty, but perfect for things like OCR, where colors need to be accurate.

+8
source

All Articles