不依赖三方库从图像数据中获取宽高-gif、bmp、png、jepg

int extract_pic_info(const BYTE *pic, const uint32_t size, int &width, int &height)
{
int ret = -;
width = ;
height = ;
size_t offset = ;
if (pic == NULL)
return ret;
if ((pic[] == 'G') && (pic[] == 'I') && (pic[] == 'F') && (pic[] == '') && (pic[] == '' || '') && (pic[] == 'a'))
{
//gif
offset = ;
width = MAKEUS(pic[offset + ], pic[offset]);
offset += ;
height = MAKEUS(pic[offset + ], pic[offset]);
ret = ;
SS_DEBUG((LM_DEBUG, "extract_pic_info: gif width(%d) height(%d)!\n", width, height));
} else if ((pic[] == 'B') && (pic[] == 'M'))
{
//BMP
offset = ;
width = MAKEUI(pic[offset + ], pic[offset + ], pic[offset + ], pic[offset + ]);
offset += ;
height = MAKEUS(pic[offset + ], pic[offset]);
ret = ;
SS_DEBUG((LM_DEBUG, "extract_pic_info: BMP width(%d) height(%d)!\n", width, height));
} else if (pic[] == png_signature[] && pic[] == png_signature[] && pic[] == png_signature[]
&& pic[] == png_signature [] && pic[] == png_signature[]
&& pic[] == png_signature[] && pic[] == png_signature[] && pic[] == png_signature[])
{
//PNG
offset = ;
width = MAKEUI(pic[offset + ], pic[offset + ], pic[offset + ], pic[offset + ]);
offset += ;
height = MAKEUI(pic[offset + ], pic[offset + ], pic[offset + ], pic[offset + ]);
ret = ;
SS_DEBUG((LM_DEBUG, "extract_pic_info: PNG width(%d) height(%d)!\n", width, height));
} else if (pic[] == && pic[] == && pic[size-] == && pic[size-] == )
{
//JPEG
bool finish = false;
offset = ;
unsigned char id = ;
while(!finish && offset < size)
{
if (pic[offset++] != 0xff || offset >= size)
{
ret = -;
SS_DEBUG((LM_DEBUG, "extract_pic_info: JPEG format error!\n"));
break;
}
id = pic[offset++];
if (id >= M_APP0 && id <= M_APPF) // app data block
{
offset += MAKEUS(pic[offset], pic[offset + ]);
continue;
}
switch(id)
{
case M_SOI:
break;
case M_COM:
case M_DQT:
case M_DHT:
case M_DNL:
case M_DRI:
offset += MAKEUS(pic[offset], pic[offset + ]);
break;
case M_SOF0:
offset += ;
height = MAKEUS(pic[offset], pic[offset + ]);
offset += ;
width = MAKEUS(pic[offset], pic[offset + ]);
finish = true;
ret = ;
SS_DEBUG((LM_DEBUG, "extract_pic_info: JPEG width(%d) height(%d)!\n", width, height));
break;
case M_SOS:
case M_EOI:
case M_DATA:
finish = true;
ret = -;
SS_DEBUG((LM_DEBUG, "extract_pic_info: JPEG can't find SOF0!\n"));
break;
default:
offset += MAKEUS(pic[offset], pic[offset + ]);
break;
}
}
}
return ret;
}

JPEG的每个标记都是由2个字节组成,其前一个字节是固定值0xFF。每个标记之前还可以添加数目不限的0xFF填充字节(fill byte)。下面是其中的8个标记:

1.   SOI 0xD 图像开始

2.   APP0 0xE0 JFIF应用数据块

3.   APPn 0xE1 - 0xEF 其他的应用数据块(n, 1~15)

4.   DQT 0xDB 量化表

5.   SOF0 0xC0 帧开始

6.   DHT 0xC4 霍夫曼(Huffman)表

7.   SOS 0xDA 扫描线开始

8.   EOI 0xD9 图像结束

不依赖三方库从图像数据中获取宽高-gif、bmp、png、jepg

上一篇:Web中的四大作用域对象


下一篇:Hystrix提高系统可用性