0

I want to read pgm file. I kept image content in byte array. When I accessed pixels, I see that some values are negative. So, I applied "& 0xFF" each byte. I hope it is ok but when I write to file, it isn't same as original image.

How can i read and write pgm p5 file?

int i = byteArray[index] & 0xFF; //reading
writer.write((char)(i)); //BufferedWriter    
Gokhan
  • 55
  • 1
  • 6

1 Answers1

1

Keep in mind that the P5 format is binary. You are using a Writer and cast the value to char. This is good for text, but not for binary data.

Instead, use an OutputStream and write the value in i directly to the stream.

int i = byteArray[index] & 0xFF; // Reading
stream.write(i); // OutputStream 

PS: If you don't feel like implementing the PGM format yourself, I have created an ImageIO plugin for the NetPBM formats (PNM) you could use. It's open source (BSD license).

Harald K
  • 26,314
  • 7
  • 65
  • 111