title: Convert 2D array in Java to Image
body: <p>I need to convert a 2D array of pixel intensity data of a grayscale image back to an image. I tried this:</p>
  
  <pre><code>BufferedImage img = new BufferedImage(
      regen.length, regen[0].length, BufferedImage.TYPE_BYTE_GRAY);  
  for(int x = 0; x &lt; regen.length; x++){
      for(int y = 0; y&lt;regen[x].length; y++){
          img.setRGB(x, y, (int)Math.round(regen[x][y]));
      }
  }
  File imageFile = new File("D:\\img\\conv.bmp");
  ImageIO.write(img, "bmp", imageFile);
  </code></pre>
  
  <p>where "regen" is a 2D double array. I am getting an output which is similar but not exact. There are few pixels that are totally opposite to what it must be (I get black color for a pixel which has a value of 255). Few gray shades are also taken as white. Can you tell me what is the mistake that I am doing?</p>