title: How to find different shades of a color in Java?
body: <p>If I have the RBG code of a number, such as <code>-16777216</code> (black), how can I find other similar shades of black using this color code?</p>
  
  <p>I'm trying to convert an image to monochrome by marking all pixels which are not <code>-16777216</code> to be white. However, often there are varying shades of black which are found, but they are lost because they are not an exact match.</p>
  
  <p>Edit: I'm having a bit of trouble. When I try to use this color to find shades of black, so I can ignore them while converting the other pixels to white, this is my result:</p>
  
  <p>Source:</p>
  
  <p><img src="https://i.stack.imgur.com/8h5Im.png" alt="source"></p>
  
  <p>Result: </p>
  
  <p><img src="https://i.stack.imgur.com/1ZSyo.png" alt="result"></p>
  
  <p>Code:</p>
  
  <pre><code>package test;
  
  import java.awt.Color;
  import java.awt.image.BufferedImage;
  import java.io.File;
  import java.net.URL;
  import javax.imageio.ImageIO;
  
  public class Test
  {       
      public static void main(String[] args)
      {
          try
          {
              BufferedImage source = ImageIO.read( new URL("http://i.imgur.com/UgdqfUY.png"));
              //-16777216 = black:
              BufferedImage dest = makeMonoChromeFast(source, -16777216);
              File result = new File("D:/result.png");
              ImageIO.write(dest, "png", result);
          }
          catch (Exception e)
          {
              e.printStackTrace();;
          }
      }
  
      public static BufferedImage makeMonoChromeFast(BufferedImage source, int foreground)
      {        
          int background = -1; //white;
  
          Color fg = new Color(foreground);
  
          int color = 0;
          for (int y = 0; y &lt; source.getHeight(); y++)
          {
              for (int x = 0; x &lt; source.getWidth(); x++)
              {
                  color = source.getRGB(x, y);
                  if ( color == foreground )
                      continue;
                  if (! isIncluded(fg, color, 50))
                      source.setRGB(x, y, background);;
              }
          }
  
          return source;
      }
  
      public static boolean isIncluded(Color target, int pixelColor, int tolerance)
      {
          Color pixel = new Color(pixelColor);
          int rT = target.getRed();
          int gT = target.getGreen();
          int bT = target.getBlue();
          int rP = pixel.getRed();
          int gP = pixel.getGreen();
          int bP = pixel.getBlue();
          return(
              (rP-tolerance&lt;=rT) &amp;&amp; (rT&lt;=rP+tolerance) &amp;&amp;
              (gP-tolerance&lt;=gT) &amp;&amp; (gT&lt;=gP+tolerance) &amp;&amp;
              (bP-tolerance&lt;=bT) &amp;&amp; (bT&lt;=bP+tolerance) );
      }
  }
  </code></pre>