Be careful to write exactly the same format you are reading. The PNM format is well defined, and you are reading it correctly. However, in the writing routine there were a couple of mistakes:
- opening a file with
"w"
or"wb"
truncates it to 0 bytes; - best practice is always to check if
fopen
succeeds; - reading actual ASCII data can be done with
fscanf
, binary data withfread
. Similarly, writing ASCII should be done withfprintf
and only binary data again withfwrite
. - If you want to make sure you write the same data as you read in before, you need to save it somewhere. The
maxval
variable is read, but not saved, and so I cannot write it back. However, it is not a huge problem because the rest of your code assumes the image is R8G8B8 anyway, and somaxval
should always be255
.
Here is an adjusted WriteImage
that works.
void WriteImage(Image *img, char *filename)
{
FILE *f = fopen(filename, "wb");
if (f == NULL)
{
printf ("Unable to open '%s' for writing!\n", filename);
/* better would be: "return -1" to indicate an error, 0 otherwise */
return;
}
fprintf (f, "P6\n");
fprintf (f, "%d %d\n", img->x, img->y);
/* actually you need to write 'maxval' here */
fprintf (f, "%d\n", 255);
fwrite(img->data, sizeof(iPixel), img->x * img->y, f);
fclose(f);
}
With the above out of the way, you can now see your 'diagonal line' is not correct! I'm not going to fix that (I suppose not being able to see what happened stopped you in your tracks), but here are a few pointers just to guide you:
- no need to return an
Image *
if you are changing data in situ anyway - no need to check every single pixel
- check the coordinates of what pixels are changed ...