title: Write pixel data in a grayscale image in java
body: <p>I am developing a project on image processing where I have to fill the digitized images of cracked paintings. I have to convert a color image to grayscale, performing some calculations on the 2D Array of the gray image and writing it back as gray image. The code for this is:</p>
  
  <pre><code>BufferedImage colorImage=ImageIO.read(new File(strImagePath));
  
              BufferedImage image = new BufferedImage(colorImage.getWidth(),colorImage.getHeight(),BufferedImage.TYPE_BYTE_GRAY);
              Graphics g = image.getGraphics();
              g.drawImage(colorImage, 0, 0, null);
              g.dispose();
  
              ImageIO.write(image,"PNG",new File("Image.PNG"));
  
              BufferedImage imgOriginal=ImageIO.read(new File("Image.PNG"));
  
              int width=image.getWidth();
              int height=image.getHeight();
  
              BufferedImage im=new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
  
              int arrOriginal[][]=new int[height][width];
  
  
              for(int i=0;i&lt;height;i++)
                  for(int j=0;j&lt;width;j++)
                      arrOriginal[i][j]=imgOriginal.getRGB(j,i)&amp; 0xFF;
  
              for(int i=0;i&lt;height;i++)
                  for(int j=0;j&lt;width;j++)
                      im.setRGB(j,i,arrOriginal[i][j]);
  
              ImageIO.write(im,"PNG",new File("Image1.PNG"));
  </code></pre>
  
  <p>But the output image is very much darker, I am not getting the original image back (I have not done any changes yet).</p>
  
  <p>I think there should be some changes in setRGB() statement but I don't know what.</p>
  
  <p>To write image back, I have also tried:</p>
  
  <p>`</p>
  
  <pre><code>BufferedImage im = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
   WritableRaster raster = im.getRaster();
   for(int i=0;i&lt;height;i++)
       for(int j=0;j&lt;width;j++)
           raster.setSample(j,i,0,arrOriginal[i][j]); 
  </code></pre>
  
  <p>`</p>
  
  <p>But it also don't give me original image back.</p>
  
  <p>Can anyone provide me the solution of this problem?
  Thanks in advance.</p>