#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int main()
{
FILE* bmp = NULL;
uint32_t offset;
uint8_t* temp = NULL;
size_t read;
unsigned int x_dim = 600, y_dim = 388;
bmp = fopen("test_colour.bmp", "r");
if (!bmp)
return -1;
/* Get the image data offset */
fseek(bmp, 10, SEEK_SET);
fgets((char*)&offset, 4, bmp);
printf("Offset = %u\n", offset);
temp = malloc(3*x_dim*y_dim*sizeof(uint8_t));
if (!temp)
return -1;
/* Go the the position where the image data is stored */
fseek(bmp, offset, SEEK_SET);
/* Copy image data to array */
printf("%u bytes requested!\n", 3*x_dim*y_dim);
read = fread((void*)temp, sizeof(uint8_t), 3*x_dim*y_dim, bmp);
printf("%Iu bytes read!\n", read);
fclose(bmp);
free(temp);
return 0;
}
我使用上述代码将24比特每像素的BMP图像的RGB数据读入一个数组。根据BMP规范,图像数据从文件开头到图像数据开始处(在BMP标题后面)的偏移量在偏移量10处给出。执行上述代码时,我得到以下输出。
Offset = 54
698400 bytes requested!
33018 bytes read!
偏移量输出看起来是正确的,因为文件大小为698454字节(=698400 + 54)。然而,
fread()
返回的值似乎表明并没有读取整个图像数据。不过,我随后使用temp
数组中的数据将RGB数据转换为灰度数据,并将这些数据再次写入BMP文件。目测检查输出图像并未出现任何错误,即使fread()
表明情况与此不同,好像我在一开始就实际读取了整个输入图像。
有人能解释这种行为吗?
fread
后,您可以检查temp
的内容,以查看它是否在读取了33018个字节后停止了吗?2)我不熟悉%Iu
格式说明符-您可以在调试器中检查read
的实际值吗? - Trebprintf
格式字符串。size_t
的格式为"%zu"
。"%Iu"
是非标准的。 如果您的实现不支持"%zu"
,则可以使用printf("%lu bytes read!\n", (unsigned long)read);
。 - Keith Thompson