简体   繁体   中英

how to read and write a ppm in Java

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&white.

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.

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<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); } 
    }    
}

Added below are three samples of a ppm file, two of which I created from a png using GIMP. http://www.sendspace.com/filegroup/HcY7Mks9SXtr9mKniVe8lSIEnYLGwsT5

See a description of the ppm format . So the error is that it starts as text , and you are using binary input. The pleasure of starting with text and then switching to bytes I leave to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM