一、概述
有時(shí)候單單獲取圖片的后綴名是無(wú)法判斷該圖片的類型,因此我們需要一種更準(zhǔn)確的識(shí)別方式:讀取圖片數(shù)據(jù)的文件識(shí)別頭。(每一個(gè)圖片都由識(shí)別頭+data組成)
二、一些已知的圖片文件頭標(biāo)識(shí)
JPEG
文件頭標(biāo)識(shí) (2 bytes): 0xff, 0xd8 (SOI) (JPEG 文件標(biāo)識(shí))
文件結(jié)束標(biāo)識(shí) (2 bytes): 0xff, 0xd9 (EOI)TGA
未壓縮的前5字節(jié) 00 00 02 00 00
RLE壓縮的前5字節(jié) 00 00 10 00 00PNG
文件頭標(biāo)識(shí) (8 bytes) 89 50 4E 47 0D 0A 1A 0AGIF
文件頭標(biāo)識(shí) (6 bytes) 47 49 46 38 39(37) 61 (G I F 8 9 (7) a)BMP
文件頭標(biāo)識(shí) (2 bytes) 42 4D (B M)PCX
文件頭標(biāo)識(shí) (1 bytes) 0ATIFF
文件頭標(biāo)識(shí) (2 bytes) 4D 4D 或 49 49ICO
文件頭標(biāo)識(shí) (8 bytes) 00 00 01 00 01 00 20 20CUR
文件頭標(biāo)識(shí) (8 bytes) 00 00 02 00 01 00 20 20IFF
文件頭標(biāo)識(shí) (4 bytes) 46 4F 52 4D (F O R M)ANI
文件頭標(biāo)識(shí) (4 bytes) 52 49 46 46(R I F F)
三、代碼判斷
+ (NSString *)sd_contentTypeForImageData:(NSData *)data {
uint8_t c;
[data getBytes:&c length:1];
switch (c) {
case 0xFF:
return @"image/jpeg";
case 0x89:
return @"image/png";
case 0x47:
return @"image/gif";
case 0x49:
case 0x4D:
return @"image/tiff";
case 0x0A:
return @"image/pca";
case 0x52:
// R as RIFF for WEBP
if ([data length] < 12) {
return nil;
}
NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
return @"image/webp";
}
return nil;
}
return nil;
}