【问题标题】:create and write to a .pgm file with FileOutputStream使用 FileOutputStream 创建并写入 .pgm 文件
【发布时间】:2021-08-16 04:59:08
【问题描述】:

我想知道是否有一种方法可以使用 FileOutputStream 类创建和写入便携式 ASCII P2 灰度图文件。 (我需要使用这个类)

这是我到目前为止所做的,但我认为这是错误的,因为我无法使用此查看器打开文件: https://smallpond.ca/jim/photomicrography/pgmViewer/index.html

public class Main {
    public static void main(String args[]){    
           
        try{    
             FileOutputStream fos = new FileOutputStream("picture.pgm");
             //create .pgm header
             //P2
             fos.write('P');  
             fos.write('2'); 
             //500x200 pixel
             fos.write(500);   
             fos.write(200);  
        
             //create black image
             for(int i=0; i< 500; i++){
                for(int k=0; k< 200; k++){
                    fos.write(0);
                } 
             }
             
            fos.close();    
                    
            }catch(IOException e){
                System.out.println(e);
            }    
      }    
}

【问题讨论】:

    标签: java fileoutputstream


    【解决方案1】:

    发生这种情况是因为您使用 .write() 希望写入 ASCII 格式的十进制数字,但它却输出了一个字节。如果您在文本编辑器中打开文件,这一点立即显而易见。

    您进一步忽略了包含灰度深度,并且数字之间缺少空格。

    要将文本写入文件,使用PrintStream 会更容易:

    import java.io.*;
    
    public class Main {
        public static void main(String args[]){
    
            try{
                 FileOutputStream fos = new FileOutputStream("picture.pgm");
                 PrintStream ps = new PrintStream(fos);
    
                 ps.println("P2");
                 ps.println("500 200");
                 // Expect gray values between 0 and 255 inclusive
                 ps.println("255");
    
                 for(int i=0; i< 500; i++){
                    for(int k=0; k< 200; k++){
                        ps.print(0);
                        // Separate numbers by space
                        ps.print(" ");
                    }
                    // Make each image line a separate text line for
                    // easier viewing in a text editor
                    ps.println();
                 }
    
                ps.close();
    
                }catch(IOException e){
                    System.out.println(e);
                }
          }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-06
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多