title: Convert an image to a 2D array and then get the image back in Java
body: <p>I want to convert an image to a 2D array of pixels, do some operations on it and then convert the resulting 2D array back to image. But I am always getting a pure black image as a result. I cannot figure out where I am going wrong. Here is what I am doing.All operations need to be done on a 8 bit grayscale image.</p>
  
  <ul>
  <li><p>Firstly I get the 2D array of pixels.</p>
  
  <pre><code>public int[][] compute(File file)
  {
  try 
  {
      BufferedImage img= ImageIO.read(file);
      Raster raster=img.getData();
      int w=raster.getWidth(),h=raster.getHeight();
      int pixels[][]=new int[w][h];
      for (int x=0;x&lt;w;x++)
      {
          for(int y=0;y&lt;h;y++)
          {
              pixels[x][y]=raster.getSample(x,y,0);
          }
      }
  
      return pixels;
  
  }
  catch (Exception e)
  {
      e.printStackTrace();
  }
  return null;
  }
  </code></pre></li>
  <li><p>Then I do some operations on the pixels array </p></li>
  <li><p>Next I convert the array back to the image.</p>
  
  <pre><code>public java.awt.Image getImage(int pixels[][])
  {
       int w=pixels.length;
       int h=pixels[0].length;
       BufferedImage image=new BufferedImage(w,h,BufferedImage.TYPE_BYTE_GRAY);
       WritableRaster raster=(WritableRaster)image.getData();
       for(int i=0;i&lt;w;i++)
       {
           for(int j=0;j&lt;h;j++)
           {
               raster.setSample(i,j,0,pixels[i][j]);
           }
       }
  
  File output=new File("check.jpg");
  try {
      ImageIO.write(image,"jpg",output);
  }
  catch (Exception e)
  {
      e.printStackTrace();
  }
  return image;
  }
  </code></pre></li>
  </ul>
  
  <p>But I get a complete black image and I am sure that it is not complete black. What should I do to get the correct results?</p>
  
  <p><strong>EDIT</strong> - After applying efan's solution, when I save the image to a file, suppose the pixel value of (0,0) is 68 then on computing the pixel value from the same file it changes sometimes to 70 sometimes to 71.. There is small distortion to each pixel.But it spoils the image as a whole. Is there any fix ?</p>