If I get a NSData which I know it's a image's data.But I don't know what format it is. So how can I identify which image format is it?Jpeg or PNG?
PS:iOS
I used Mats answer to build a simple category on NSData which tells me if its content is JPEG or PNG based on its first 4 bytes:
@interface NSData (yourCategory)
- (BOOL)isJPG;
- (BOOL)isPNG;
@end
@implementation NSData (yourCategory)
- (BOOL)isJPG
{
if (self.length > 4)
{
unsigned char buffer[4];
[self getBytes:&buffer length:4];
return buffer[0]==0xff &&
buffer[1]==0xd8 &&
buffer[2]==0xff &&
buffer[3]==0xe0;
}
return NO;
}
- (BOOL)isPNG
{
if (self.length > 4)
{
unsigned char buffer[4];
[self getBytes:&buffer length:4];
return buffer[0]==0x89 &&
buffer[1]==0x50 &&
buffer[2]==0x4e &&
buffer[3]==0x47;
}
return NO;
}
@end
And then, simply do a :
CGDataProviderRef imgDataProvider = CGDataProviderCreateWithCFData((CFDataRef) imgData);
CGImageRef imgRef = nil;
if ([imgData isJPG])
imgRef = CGImageCreateWithJPEGDataProvider(imgDataProvider, NULL, true, kCGRenderingIntentDefault);
else if ([imgData isPNG])
imgRef = CGImageCreateWithPNGDataProvider(imgDataProvider, NULL, true, kCGRenderingIntentDefault);
UIImage* image = [UIImage imageWithCGImage:imgRef];
CGImageRelease(imgRef);
CGDataProviderRelease(imgDataProvider);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With