How to get the width/height of jpeg file without u

2020-02-17 10:29发布

Firstly I want to say I tried many times to find the answer by using google search, and I found many results but I did not understand, because I don't know the idea of reading a binary file, and convert the value that Obtained to readable value.

What I tried doing it.

unsigned char fbuff[16];
FILE *file;
file = fopen("C:\\loser.jpg", "rb");
if(file != NULL){
   fseek(file, 0, SEEK_SET);
   fread(fbuff, 1, 16, file);
   printf("%d\n", fbuff[1]);
   fclose(file);
}else{
   printf("File does not exists.");
}

I want a simple explanation with example shows, how to get width/height of jpeg file from its header, and then convert that value to readable value.

7条回答
走好不送
2楼-- · 2020-02-17 11:22

Here's a code i wrote in Java. Works fine for jpegs taken from a camera. It scans all the code to find the biggest image size. I could not improve it to skip on the lengths of each block because it doesn't work. If anyone can improve the code to do that it would be great.

int getShort(byte[] p, int i)
{
   int p0 = p[i] & 0xFF;
   int p1 = p[i+1] & 0xFF;
   return p1 | (p0 << 8);
}

int[]  GetJpegDimensions(byte[] b)
{
    int nIndex;
    int height=0, width=0, size=0;
    int nSize = b.length;

    // marker FF D8  starts a valid JPEG
    if (getShort(b,0) == 0xFFD8)
       for (nIndex = 2; nIndex < nSize-1; nIndex += 4)
          if (b[nIndex] == -1/*FF*/ && b[nIndex+1] == -64/*C0*/)
          {
             int w = getShort(b,nIndex+7);
             int h = getShort(b,nIndex+5);
             if (w*h > size)
             {
                size = w*h;
                width = w;
                height = h;
             }
          }
    return new int[]{width,height};
}
查看更多
登录 后发表回答