1. 程式人生 > >圖片型別判斷

圖片型別判斷

1.JPEG/JPG - 檔案頭標識 (2 bytes): $ff, $d8 (SOI) (JPEG 檔案標識) - 檔案結束標識 (2 bytes): $ff, $d9 (EOI) 
2.TGA            - 未壓縮的前5位元組                    00 00 02 00 00     -        RLE壓縮的前5位元組       00 00 10 00 00
3.PNG            - 檔案頭標識 (8 bytes)             89 50 4E 47 0D 0A 1A 0A
4.GIF              - 檔案頭標識 (6 bytes)             47 49 46 38 39(37) 61                         G  I  F  8  9 (7)  a
5.BMP            - 檔案頭標識 (2 bytes)             42 4D                         B  M
6.PCX            - 檔案頭標識 (1 bytes)             0A
7.TIFF             - 檔案頭標識 (2 bytes)            4D 4D 或 49 49
8.ICO               - 檔案頭標識 (8 bytes)            00 00 01 00 01 00 20 20 
9.CUR             - 檔案頭標識 (8 bytes)            00 00 02 00 01 00 20 20
10.IFF             - 檔案頭標識 (4 bytes)             46 4F 52 4D         
 

給出C++程式碼判斷bmp跟jpeg:

bool IsBitmap(const char* pstrFileName)
{
    if(!pstrFileName){

        return false;

    }

    if(access(pstrFileName, F_OK) == -1){
        return false;
    }

    unsigned char btData[2] = {0};
    FILE* pFile = fopen(pstrFileName, "rb+");
    if(pFile){
        fseek(pFile, 0, SEEK_END);
        long nLen = ftell(pFile);
        fseek(pFile, 0, SEEK_SET);
        fread(btData, sizeof(unsigned char), sizeof(unsigned char) * 2, pFile);
        fclose(pFile);
    }
    if(btData[0] ==0x42 && btData[1] ==0x4d){
        return true;
    }
    return false;
}
bool IsJpeg(const char* pstrFileName)
{
    if(!pstrFileName){

        return false;

    }

    if(access(pstrFileName, F_OK) == -1){
        return false;
    }

    unsigned char btHeader[2] = {0};
    unsigned char btTail[2] = {0};
    FILE* pFile = fopen(pstrFileName, "rb+");
    if(pFile){
        fseek(pFile, 0, SEEK_END);
        long nLen = ftell(pFile);
        fseek(pFile, 0, SEEK_SET);
        fread(btHeader, sizeof(unsigned char), sizeof(unsigned char) * 2, pFile);
        fseek(pFile, nLen - sizeof(unsigned char) * 2, SEEK_SET);
        fread(btTail, sizeof(unsigned char), sizeof(unsigned char) * 2, pFile);
        fclose(pFile);
    }
    if(btHeader[0] ==0xff && btHeader[1] ==0xd8 && btTail[0] ==0xff && btTail[1] ==0xd9){
        return true;
    }
    return false;
}