问题描述
我想知道是否有办法使用 FileOutputStream 类创建和写入便携式 ASCII P2 灰度图文件。 (我需要使用这个类)
这是我到目前为止所做的,但我认为这是错误的,因为我无法使用此查看器打开文件: https://smallpond.ca/jim/photomicrography/pgmViewer/index.html
@font-face {
src: url('/../fonts/custom-font.woff');
font-family: "custom-font" !important;
}
h1,h2,h3,h4,h5,h6 {
font-family: "custom-font" !important;
解决方法
发生这种情况是因为您使用 .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);
}
}
}