I am trying to write a PGM file in a C program, but once it is written, if I try to open it to view the image I am told the image file format can’t be determined.
However, if I create a new file in geany, copy the data over, and then save THAT as a new PGM, it works.
Any idea why this could be?
FILE * grey = fopen("greyscale.pgm", "w");
fprintf(grey, "P2 \r\n%d %d \r\n255 \r\n", width, height);
for (i = 0; i < width; i++) {
for (j = 0; j < height; j++) {
fprintf(grey, "%d ", ((imageArray[i][j].red + imageArray[i][j].green + imageArray[i][j].blue)/3));
}
fprintf(grey, "\r\n");
}
I am converting a colour image to greyscale.
I think you should not use
\r\nas a line delimiter, but only\n. Also, check that no line has above 70 characters in length. Since each pixel needs at most 4 characters (3 plus space) insert\nafter every 17 pixels.You can separate real lines with comments (for example: