从jpeg图像文件获取宽度和高度

Jac*_*ack 3 c height jpeg width

我把这个函数写成给定的文件名(一个jpeg文件)应该以像素为单位打印它的大小,w和h.根据我正在阅读的教程,

// 0xFFC0是"帧起始"标记,包含文件大小// 0xFFC0块的结构非常简单[0xFFC0] [ushort length] [uchar precision] [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()
Run Code Online (Sandbox Code Playgroud)

然后:

#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);
    }
Run Code Online (Sandbox Code Playgroud)

但我得到的520x537不是700x537,那是真正的大小.

有人能指出并解释我错在哪里吗?

n. *_* m. 8

JPEG文件由许多部分组成.每个部分0xff以1字节的段标识符开头,后跟段中的数据字节数(以2个字节为单位),后跟数据字节.数据字节序列内的序列0xffc0或任何其他0xff--双字节序列没有意义,也没有标记段的开头.

作为例外,第一部分不包含任何数据或长度.

您必须依次读取每个节头,解析长度,然后在开始阅读下一节之前跳过相应的字节数.你不能只是搜索0xffc0,更不用说0xc0,而不考虑部分结构.

来源.