//枚举定义图片类型
{
NSPUIImageType_JPEG,
NSPUIImageType_PNG,
NSPUIImageType_GIF,
NSPUIImageType_Unknown
};
//定义方法
static inline NSPUIImageType NSPUIImageTypeFromData(NSData *imageData) { if (imageData.length > 4) { const unsigned char * bytes = [imageData bytes]; if (bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff) { return NSPUIImageType_JPEG; } if (bytes[0] == 0x89 && bytes[1] == 0x50 && bytes[2] == 0x4e && bytes[3] == 0x47) { return NSPUIImageType_PNG; } if (bytes[0] == 0x47) { return NSPUIImageType_GIF; } } return NSPUIImageType_Unknown; }
//调用
NSURL *url = [NSURL URLWithString:@"http://g.hiphotos.baidu.com/image/pic/item/c2cec3fdfc03924578c6cfe18394a4c27c1e25e8.jpg"]; NSData *data = [NSData dataWithContentsOfURL:url]; //NSData *data = [NSData dataWithContentsOfFile:@"/Users/apple/Desktop/book_cover.png"]; NSPUIImageType type = NSPUIImageTypeFromData(data); if (type == NSPUIImageType_JPEG) { NSLog(@"JPEG"); }else if (type == NSPUIImageType_PNG) { NSLog(@"PNG"); }else if (type == NSPUIImageType_PNG) { NSLog(@"GIF"); }else { NSLog(@"Unknown"); }