How to get the width/height of jpeg file without using library?

后端 未结 7 1694
清歌不尽
清歌不尽 2020-12-25 08:43

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 read

7条回答
  •  长情又很酷
    2020-12-25 09:16

    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};
    }
    

提交回复
热议问题