欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

判断图片格式

程序员文章站 2024-02-18 18:29:46
...
string getImageFileFormat(string fileName)
{
    unsigned short  BMP=0x4D42,
            JPG=0xD8FF,
            PNG[4]={0x5089,0x474E,0x0A0D,0x0A1A},
            GIF[3]={0x4947,0x3846,0x6139};

    FILE *fis;
    unsigned short pis[8];
    string fileFormat = "null";
    if((fis=fopen(fileName.c_str(),"r"))==NULL)
    {
        cout << getTimeZZ() << "can not read " << fileName << endl;
        return "null";
    }
    fread(pis,8,1,fis);
    if(pis[0]==BMP)
    {
        cout << getTimeZZ() << "it is a bmp "<< endl;
        fileFormat =  "bmp";
    }
    else if(pis[0]==JPG)
    {
        cout << getTimeZZ() << "it is a jpg "<< endl;
        fileFormat = "jpg";
    }
    else if(PNG[0]==pis[0]&&PNG[1]==pis[1]&&PNG[2]==pis[2]&&PNG[3]==pis[3])
    {
        cout << getTimeZZ() << "it is a png"<< endl;
        fileFormat = "png";
    }
    else if(GIF[0]==pis[0]&&GIF[1]==pis[1]&&GIF[2]==pis[2])
    {
        cout << getTimeZZ() << "it is a gif"<< endl;
        fileFormat = "gif";
    }
    return fileFormat;
}