C language common picture format judgment example

  • 2020-04-02 01:40:19
  • OfStack

I want to think about everything. Today, I finally got the picture judged.

Here, let me write down my ideas. Hopefully for those of you who don't want to see the code.

Constant wind of the image format: BMP, PNG, JPG, GIF and other image formats.

The method I use is to read the identifier in the image header file:


unsigned short  BMP=0x4D42,
JPG=0xD8FF,
PNG[4]={0x5089,0x474E,0x0A0D,0x0A1A},
GIF[3]={0x4947,0x3846,0x6139};

And you'll see that it reads n bytes at a time in a different order; The order of opening with "okhit" is different.

Don't worry about it.

With that in mind, the next step is judgment. This is hard to say in Chinese, please look at the original code.

I'm using an if else structure.

You may not be able to open the file when you compile it. Please note: open file name


int main()
{
    FILE *fis;
    short int i=0;
    unsigned short pis[5];
    if((fis=fopen("1.bmp","r"))==NULL) 
        printf("can not read %sn","1.bmp");

    fread(pis,8,1,fis);
    for(i=0;i<4;++i)
        printf("%0x..",pis[i]);
    printf("n");
        if(pis[0]==BMP)    
          printf("it is a bmpn");
          else if(pis[0]==JPG)    
            printf("it is a jpgn");
            else if(PNG[0]==pis[0]&&PNG[1]==pis[1]&&PNG[2]==pis[2]&&PNG[3]==pis[3])    
              printf("it is a pngn");
              else if(GIF[0]==pis[0]&&GIF[1]==pis[1]&&GIF[2]==pis[2])    
            printf("it is a gifn");
    return 0;
}

In order to facilitate the call, a function is made:


int istupian(char entry[])

{
    FILE *fis;
    short int i=0;
    unsigned short pis[5];
    int flag=0;//Each call is initialized
    if((fis=fopen(entry,"r"))==NULL) 
        printf("can not read %sn",entry);
    fread(pis,8,1,fis);

    if(pis[0]==BMP)    
    {
        flag=1;        
        printf("it is a bmpn");
    }
    else if(pis[0]==JPG)    
    {
        flag=2;
        printf("it is a jpgn");
    }
    else if(PNG[0]==pis[0]&&PNG[1]==pis[1]&&PNG[2]==pis[2]&&PNG[3]==pis[3])    
    {
        flag=3;        
        printf("it is a pngn");
    }
    else if(GIF[0]==pis[0]&&GIF[1]==pis[1]&&GIF[2]==pis[2])    
    {
        flag=4;        
        printf("it is a gifn");
    }
    return flag;

}


Related articles: