title: How to convert a BufferedImage to black and white?
body: <p>How can I convert an existing colored BufferedImage to monochrome? I want the image to be completely split between only two rgb codes, black and white. So if there's a border around the image which is a lighter or darker shade of the background, and the background is being converted to white, then I want the border to be converted to white as well, and so on.</p>
  
  <p>How can I do this?</p>
  
  <p>If its necessary to save the image / load it from disk, I can do that if necessary.</p>
  
  <p><strong>Edit:</strong> Code to test this:</p>
  
  <pre><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&lt;Integer&gt; colors = new HashSet&lt;&gt;();
              int color = 0;
              for (int y = 0; y &lt; gray.getHeight(); y++)
              {
                  for (int x = 0; x &lt; 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();
          }
      }
  }
  </code></pre>
  
  <p>Image used:</p>
  
  <p><img src="https://i.stack.imgur.com/yhCnH.png" alt="image"></p>
  
  <p>Using this, I get the output of 24 as the last output, i.e there were 24 colors found in this image, when there should be 2.</p>