Tuesday, 20 August 2013

Convert a P6 PPM image to P3 PPM image

Convert a P6 PPM image to P3 PPM image

I am trying to write a converter from P6 to P3, which means from data
saved in binary to data saved in ASCII.
This is the function I wrote to do the job but red,green and blue integers
get garbage values instead of their decimal value.
int convertP6toP3(char* fileName)
{
FILE *src, *dest;
char *outputFilename;
char magicNumber[3];
int height, width, depth;
int red = 0, green = 0, blue = 0;
int i, j, widthCounter = 1;
if (checkFileExists(fileName) == FALSE)
{
printf("- Given file does not exists!\n");
return ERROR;
}
else
src = fopen(fileName, "rb");
outputFilename = getOutputFilename(fileName, ".p3.ppm");
dest = fopen(outputFilename, "w+");
// check that the input file is actually in P6 format
fscanf(src, "%s", magicNumber);
if (strcmp(magicNumber, "P6") != 0)
return ERROR;
fscanf(src, "%d %d %d", &height, &width, &depth);
fprintf(dest, "P3\n");
fprintf(dest, "#P3 converted from P6\n");
fprintf(dest, "%d %d\n%d\n", height, width, depth);
for (i = 0; i < width*height; i++)
{
for (j = 0; j < 3; j++)
{
fread(&red, sizeof(int), 1, src);
fread(&green, sizeof(int), 1, src);
fread(&blue, sizeof(int), 1, src);
}
for (j = 0; j < 3; j++)
fprintf(dest, "%d %d %d ", red, green, blue);
if (widthCounter == width)
{
fprintf(dest, "\n");
widthCounter = 1;
}
else
widthCounter++;
}
free(outputFilename);
fclose(src);
fclose(dest);
return TRUE;
}
What am I doing wrong with reading the binary data? The height, width and
depth are read flawlessly.

No comments:

Post a Comment