我正在尝试编写一个从 P6 到 P3 的转换器,这意味着从以二进制保存的数据到以 ASCII 保存的数据。
这是我为完成这项工作而编写的函数,但是整数red
得到的是垃圾值而不是十进制值。green
blue
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;
}
我在读取二进制数据时做错了什么?高度、宽度和深度被完美读取。
编辑:在尝试使用读取数据大小后,我得到了一些我无法解释的疯狂结果: