我将此函数写入给定文件名(一个jpeg文件)应以像素,w和h为单位打印其大小。根据教程,我读,从jpeg图像文件中获取宽度和高度
// 0xFFC0是包含文件大小 //所述0xFFC0块的结构的“帧开始”标记是相当简单的[0xFFC0] [USHORT 长度] [UCHAR精度] [USHORT X] [USHORT Y]
所以,我写了这个struct
#pragma pack(1)
struct imagesize {
unsigned short len; /* 2-bytes */
unsigned char c; /* 1-byte */
unsigned short x; /* 2-bytes */
unsigned short y; /* 2-bytes */
}; //sizeof(struct imagesize) == 7
#pragma pack()
然后:
#define SOF 0xC0 /* start of frame */
void jpeg_test(const char *filename)
{
FILE *fh;
unsigned char buf[4];
unsigned char b;
fh = fopen(filename, "rb");
if(fh == NULL)
fprintf(stderr, "cannot open '%s' file\n", filename);
while(!feof(fh)) {
b = fgetc(fh);
if(b == SOF) {
struct imagesize img;
#if 1
ungetc(b, fh);
fread(&img, 1, sizeof(struct imagesize), fh);
#else
fread(buf, 1, sizeof(buf), fh);
int w = (buf[0] << 8) + buf[1];
int h = (buf[2] << 8) + buf[3];
img.x = w;
img.y = h;
#endif
printf("%dx%d\n",
img.x,
img.y);
break;
}
}
fclose(fh);
}
但我得到520x537
而不是700x537
,这是真正的大小。
有人可以指出并解释我错了吗?
+1非常好的解释,我陷入了同样的陷阱。小提示:有一些部分不遵循一般方案,即SOI(图像开始,你提到的,0xffd8),RSTn(重启标记,0xffdn,n = 0..7)和EOI(结束图像,0xffd9)。 DRI(0xffdd)遵循该方案,但长度值始终为4. http://en.wikipedia.org/wiki/Jpeg#Syntax_and_structure – ThomasH