在Java中读取和写入原始PGM文件

在Java中读取和写入原始PGM文件,java,pgm,Java,Pgm,我正在尝试读取和写入PGM文件。使用ASCII PGM(幻数=P2)很容易,但我在使用原始PGM文件(幻数P5)时有些困惑 以下是我正在尝试读取的PGM文件: 在PGM头之后,当我尝试使用以下Java代码读取图像数据时: FileInputStream inRaw = null; try { inRaw = new FileInputStream("A.pgm"); } catch (FileNotFoundException e) { e.printStackTrace();

我正在尝试读取和写入PGM文件。使用ASCII PGM(幻数=P2)很容易,但我在使用原始PGM文件(幻数P5)时有些困惑

以下是我正在尝试读取的PGM文件:

在PGM头之后,当我尝试使用以下Java代码读取图像数据时:

FileInputStream inRaw = null;
try {
    inRaw = new FileInputStream("A.pgm");
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
Scanner scan_Raw = new Scanner(inRaw);
//lines to read the PGM Header
System.out.println(scan_Raw.nextLine());
System.out.println(scan_Raw.nextLine());
System.out.println(scan_Raw.nextLine());
System.out.println(scan_Raw.nextLine());
//Code to read the Image Data
while(scan_Raw.hasNext()){
    System.out.println(scan_Raw.next());
然后给出以下输出:

�����������������������������������������������������������������������������������������#F�����������������   ����������������}   ����������������; > e���������������� #��������������� 7� ��������������v y�M ��������������4 
`�������������     
������������� A��� ������������p ����U ������������n�����
��������������������������������������������������������������������������������������
这个输出是什么?
这也是为什么我无法使用
scan_Raw.nextByte()读取while(输入不匹配异常)因为据我所知,P5中的图像数据保存为字节?

问题是,您不能使用
扫描仪(用于文本输入)解析原始字节。相反,仅使用扫描仪解析标题,然后-如果格式为
P5
-使用
read()
read(b,off,len)
方法直接从
InputStream
读取字节。在许多方面,读取
P5
格式实际上更容易,因为数据已经是
buffereImage使用的本机格式。键入\u BYTE\u GRAY
。PS:我假设您想为教育目的编写自己的读写器。如果没有,请查看my,它支持读取PBM、PGM、PPM和其他衍生产品。@haraldK是的,它用于学习。谢谢你的插件,我可以从中学习。