How to convert color image to pure black and white image(0-255 format)

Yogesh picture Yogesh · Feb 13, 2013 · Viewed 11.6k times · Source
public class BlackWhite {

    public static void main(String[] args) 
    {
        try 
        {
         BufferedImage original = ImageIO.read(new File("colorimage"));
         BufferedImage binarized = new BufferedImage(original.getWidth(), original.getHeight(),BufferedImage.TYPE_BYTE_BINARY);

         int red;
         int newPixel;
         int threshold =230;

            for(int i=0; i<original.getWidth(); i++) 
            {
                for(int j=0; j<original.getHeight(); j++)
                {

                    // Get pixels
                  red = new Color(original.getRGB(i, j)).getRed();

                  int alpha = new Color(original.getRGB(i, j)).getAlpha();

                  if(red > threshold)
                    {
                        newPixel = 0;
                    }
                    else
                    {
                        newPixel = 255;
                    }
                    newPixel = colorToRGB(alpha, newPixel, newPixel, newPixel);
                    binarized.setRGB(i, j, newPixel);

                }
            } 
            ImageIO.write(binarized, "jpg",new File("blackwhiteimage") );
         }
        catch (IOException e) 
        {
                e.printStackTrace();
        }    
    }

     private static int colorToRGB(int alpha, int red, int green, int blue) {
            int newPixel = 0;
            newPixel += alpha;
            newPixel = newPixel << 8;
            newPixel += red; newPixel = newPixel << 8;
            newPixel += green; newPixel = newPixel << 8;
            newPixel += blue;

            return newPixel;
        }
}

I got a black and white output image, but as I zoomed the image I discovered some gray area. I want the output image to only contain the colors black or white.

Please let me know if I am correct or incorrect in my current approach? And if I am, please suggest another way.

Answer

iTech picture iTech · Feb 13, 2013

You are converting the image correctly from color to black and white; however, when you save the output as JPEG some colors are created as a result of the lossy compression.

Simply save the output to PNG (or anything other than JPEG), and the output will be only black and white, as you had expected.

ImageIO.write(binarized, "png",new File("blackwhiteimage") );

For example, if you have a binary image that saved as PNG the histogram can be something like (strictly black and white pixels only):

PNG histogram

And for the same image if you saved as JPEG, you can see that in the histogram some pixels near the white and black color start to appear

JPEG histogram