title: how to read and write a ppm in Java
body: <p>I'm solving old exams. In Java, I would like to open an image file input.ppm, convert it to greyscale, and save it as output.ppm. So I have to read all its contents (RGB information for each pixel), take the average value and save it three times, so that the pixel becomes black&amp;white.</p>
  
  <p>The following code does notr work properly. The width and height are not correct. Also, the file output.ppm is empty. And the RGB values are not read correctly.</p>
  
  <pre><code>import java.io.DataInputStream; 
  import java.io.DataOutputStream; 
  import java.io.File; 
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.IOException;
  
  public class slika {
  
      public static void main(String[] args){ 
          File input = new File("input.ppm"); 
          File output = new File("output.ppm"); 
  
          try{DataInputStream in = new DataInputStream(new FileInputStream(input));
              DataOutputStream out = new DataOutputStream(new FileOutputStream(output));
              in.read(); 
              int w=in.readInt(); //System.out.println("width="+w);
              int h=in.readInt(); //System.out.println("height="+h);
              in.read();
              for(int i=0; i&lt;w*h; i++){ 
                  int r=in.read(); //System.out.println("red="r);
                  int g=in.read(); //System.out.println("green="g);
                  int b=in.read(); //System.out.println("blue="b);
                  int avg=(r+g+b)/3; //greyscale pixels
                  out.write(avg);
                  out.write(avg);
                  out.write(avg);
              }
              in.close();
              out.close();
          } catch (IOException ex) { System.err.println(ex); } 
      }    
  }
  </code></pre>
  
  <p>Added below are three samples of a ppm file, two of which I created from a png using GIMP.
  <a href="http://www.sendspace.com/filegroup/HcY7Mks9SXtr9mKniVe8lSIEnYLGwsT5" rel="nofollow">http://www.sendspace.com/filegroup/HcY7Mks9SXtr9mKniVe8lSIEnYLGwsT5</a></p>