title: How to threshold and BufferedImage in Java
body: <p>I have read my original image as BufferedImage in Java and then following some operations, I am trying to threshold my image to either high(255) or low(0) but when I save my image, actually I try to overwrite it with new values, the pixels value are not only 0 and 255, some neighbouring values appear, I don't understand why.</p>
  
  <p><strong>READING MY IMAGE</strong></p>
  
  <pre><code>File input = new File("/../Screenshots/1.jpg");
  BufferedImage image = ImageIO.read(input);
  for (int i = 0; i &lt; image.getWidth(); i++) {
          for (int j = 0; j &lt; image.getHeight(); j++) {
              Color c = new Color(image.getRGB(i, j));
              powerspectrum[i][j] = (int) ((c.getRed() * 0.299)
                      + (c.getGreen() * 0.587) + (c.getBlue() * 0.114));
          }
      }
  </code></pre>
  
  <p><strong>THRESHOLDING MY IMAGE</strong></p>
  
  <pre><code>for (int i = 0; i &lt; image.getWidth(); i++) {
          for (int j = 0; j &lt; image.getHeight(); j++) {
              if (gradient[i][j] &lt;= upperthreshold
                      &amp;&amp; gradient[i][j] &gt;= lowerthreshold)
                  spaces[i][j] = 255;
              else
                  spaces[i][j] = 0;
              Color gradColor = new Color(spaces[i][j], spaces[i][j],
                      spaces[i][j]);
              image.setRGB(i, j, gradColor.getRGB());
          }
      }
  </code></pre>
  
  <p><strong>SAVING MY IMAGE</strong></p>
  
  <pre><code>File gradoutput = new File("/../Screenshots/3_GradThresh.jpg");
      ImageIO.write(image, "jpg", gradoutput);
  </code></pre>
  
  <p>I don't know how to cut off the other intensity values.</p>