I need to read a pgm file and store the array of values contained in it in a 2D array. In PGM format, each pixel is specified by a gray value between 0 and MaxVal. The first three lines give information related to the image: magic number, height, width and maxVal. The file also includes whitespaces. Lines starting with # are comments. This is what I had written till now.
public class PGM{
public static void main(String args[]) throws Exception {
FileInputStream f = new FileInputStream("C:\\......\\brain_001.pgm");
DataInputStream d = new DataInputStream(f);
d.readLine();//first line contains P5
String line = d.readLine();//second line contains height and width
Scanner s = new Scanner(line);
int width = s.nextInt();
int height = s.nextInt();
line = d.readLine();//third line contains maxVal
s = new Scanner(line);
int maxVal = s.nextInt();
byte[][] im = new byte[height][width];
for (int i = 0; i < 258; i++) {
for (int j = 0; j < 258; j++) {
im[i][j] = -1;
}
}
int count = 0;
byte b;
try {
while (true) {
b = (byte) (d.readUnsignedByte());
if (b == '\n') { //do nothing if new line encountered
} else if (b == '#') {
d.readLine();
} else if (Character.isWhitespace(b)) { // do nothing if whitespace encountered
} else {
im[count / width][count % width] = b;
count++;
}
}
} catch (EOFException e) {
}
System.out.println("Height=" + height);
System.out.println("Width=" + height);
System.out.println("Required elemnts=" + (height * width));
System.out.println("Obtained elemnets=" + count);
}
}
When the program is run, I get the following output:
Height=258
Width=258
Required elemnts=66564
Obtained elemnets=43513
The number of elements (each corresponding to a gray value) are less than the required ones. When I open the file with a PGM viewer, everything shows up correctly. Also, when I print the contents of the array, I see a lot of negative values. But all of them have to be greater than or equal to zero. Where have I gone wrong?