How to determine the image format of NSData?

If I get NSData, which I know is image data. But I do not know what format it is. So how can I determine which image format this is? Jpeg or PNG?

PS: iOS

+6
source share
5 answers

You can look at the first bytes and make an assumption. There are many lists of magic numbers available on the Internet, for example. http://www.astro.keele.ac.uk/oldusers/rno/Computing/File_magic.html

+8
source

I used Mats to create a simple category in NSData that tells me whether its contents are 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 just do:

 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); 
+15
source

Here is a quick version of @apouche's answer:

 extension NSData { func firstBytes(length: Int) -> [UInt8] { var bytes: [UInt8] = [UInt8](count: length, repeatedValue: 0) self.getBytes(&bytes, length: length) return bytes } var isJPEG: Bool { let signature:[UInt8] = [0xff, 0xd8, 0xff, 0xe0] return firstBytes(4) == signature } var isPNG: Bool { let signature:[UInt8] = [0x89, 0x50, 0x4e, 0x47] return firstBytes(4) == signature } } 
+1
source

Can you create an image from this, and then just ask what NSImage is in what format?

You can use -initWithData to create NSImage, see http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSImage_Class/Reference/Reference.html for more details

0
source

You can create a CGImageSourceRef and then set the image type

  CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef) imageData, NULL); if(imageSource) { // this is the type of image (eg, public.jpeg - kUTTypeJPEG ) // <MobileCoreServices/UTCoreTypes.h> CFStringRef UTI = CGImageSourceGetType(imageSource); CFRelease(imageSource); } imageSource = nil; 
0
source

Source: https://habr.com/ru/post/896470/


All Articles