23,116
社区成员
发帖
与我相关
我的任务
分享
#include <png.h>
int detect_png(char* file)
{
int tempi;
char buff[100];
fp = fopen(file, "rb");
png_structp png_ptr;
png_infop info_ptr;
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
info_ptr = png_create_info_struct(png_ptr);
setjmp(png_jmpbuf(png_ptr));
// 这句很重要
//检测是否为png图片
fread(buff,1,13,fp);
tempi = png_sig_cmp(buff,(png_size_t)0,13);
if (tempi != 0){//如果不是png图片
fclose(fp);
return 1;
}
rewind(fp);
png_init_io(png_ptr,fp);
// 读文件了
png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_EXPAND, 0);
// 得到文件的宽、高、位深
image_width = png_get_image_width(png_ptr, info_ptr);
image_hight = png_get_image_height(png_ptr, info_ptr);
image_depth = png_get_bit_depth(png_ptr, info_ptr);
fclose(fp);
return 0;
}
typedef struct bmp_head {
//bmp头文件
short int BMPsyg;
short int nic[8];
short int ix;
short int nic2;
short int iy;
short int nic3[2];
short int depth;
short int rle;
short int nic4[11];
} bmp_head;
int detect_bmp(char *file)
//检测bmp图片信息
{
bmp_head bmp;
fp = fopen(file,"r");//打开图片文件
fread(&bmp,1,sizeof(bmp_head),fp);//读取数据
if (bmp.BMPsyg != 19778)
{
fclose(fp);
return 1;
}
image_width = bmp.ix;//图片的宽度
image_hight = bmp.iy;//图片的高度
image_depth = bmp.depth;//图片的位深
fclose(fp);
return 0;
}
int ParsePic(BYTE *pHead, int &iWidth, int &iHeight)
{
BYTE n[4];
n[0]=pHead[0];
n[1]=pHead[1];
n[2]=pHead[2];
n[3]=pHead[3];
int i=1;
if(n[0] == 0xFF && n[1] == 0xD8) //jpeg //图片类型0
{
i=iWidth<40000?iWidth-1000:30000;
while(i>20)
{
i--;
if(pHead[i] < 0xC0) continue;
if(pHead[i] > 0xC3) continue;
i--;
if(pHead[i] != 0xFF) continue;
i+=5;
break;
}
if(i<=20) return -1;
iHeight=pHead[i]*256+pHead[i+1];
i+=2;
iWidth=pHead[i]*256+pHead[i+1];
return 0;
}
if(n[0] == 'G' && n[1] == 'I' && n[2] == 'F') //gif //图片类型3
{
iWidth=pHead[7]*256+pHead[6];
iHeight=pHead[9]*256+pHead[8];
return 3;
}
if(n[0] == 'B' && n[1] == 'M') //bmp //图片类型2
{
iWidth=pHead[19]*256+pHead[18];
iHeight=pHead[23]*256+pHead[22];
return 2;
}
if(n[0] == 0x89 && n[1] == 0x50 && n[2] == 0x4E && n[3] == 0x47) //png //图片类型1
{
while(i<iWidth)//length
{
i++;
if(pHead[i] != 0x49) continue;
i++;
if(pHead[i] != 0x48) continue;
i++;
if(pHead[i] != 0x44) continue;
i++;
if(pHead[i] != 0x52) continue;
i++;
if(i > iWidth-10) return -2;
break;
}
iWidth=pHead[i+2]*256+pHead[i+3];
iHeight=pHead[i+6]*256+pHead[i+7];
return 1;
}
return -1;
}