简体   繁体   English

如何在Java中读写ppm

[英]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. 在Java中,我想打开一个图像文件input.ppm,将其转换为灰度,然后将其另存为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. 因此,我必须读取所有内容(每个像素的RGB信息),取平均值并将其保存3次,以使像素变为黑白。

The following code does notr work properly. 以下代码无法正常工作。 The width and height are not correct. 宽度和高度不正确。 Also, the file output.ppm is empty. 同样,文件output.ppm为空。 And the RGB values are not read correctly. 并且无法正确读取RGB值。

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. 以下添加的是一个ppm文件的三个示例,其中两个是我使用GIMP从png创建的。 http://www.sendspace.com/filegroup/HcY7Mks9SXtr9mKniVe8lSIEnYLGwsT5 http://www.sendspace.com/filegroup/HcY7Mks9SXtr9mKniVe8lSIEnYLGwsT5

See a description of the ppm format . 请参阅ppm格式的说明。 So the error is that it starts as text , and you are using binary input. 因此错误是它以text开头,并且您正在使用二进制输入。 The pleasure of starting with text and then switching to bytes I leave to you. 从文本开始然后切换到字节的乐趣,我留给您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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