Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify a NSData's image format?

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

like image 541
Jimmy Avatar asked Sep 02 '11 09:09

Jimmy


1 Answers

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);
like image 167
apouche Avatar answered Sep 21 '22 02:09

apouche