作为一项家庭作业,我们应该读入一个 .pgm 文件,然后通过更改像素值来绘制一个正方形,然后输出新图像。在我完成并更改像素后,我将它们全部打印到 .txt 中,以检查它们是否真的被添加了。我遇到问题的部分是编写新文件。我知道它应该是二进制的,所以在谷歌搜索后我认为我应该使用 DataOutputStream,但我可能是错的。在我写完文件后,它的大小是 1.9MB,而原始文件只有 480KB,所以我马上就怀疑一定有问题。任何关于写入 .pgm 文件的建议或技巧都会很棒!
public static void writeImage(String fileName) throws IOException{
DataOutputStream writeFile = new DataOutputStream(new FileOutputStream(fileName));
// Write the .pgm header (P5, 800 600, 250)
writeFile.writeUTF(type + "\n");
writeFile.writeUTF(width + " " + height + "\n");
writeFile.writeUTF(max + "\n");
for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++){
writeFile.writeByte(img[i][j]); //Write the number
writeFile.writeUTF(" "); //Add white space
}
writeFile.writeUTF(" \n"); //finished one line so drop to next
}
writeFile.close();
}
当我尝试打开新文件时,我收到一条错误消息,提示“非法图像格式”,并且原始文件可以正常打开。