如何识别NSData的图像格式?

时间:2011-09-02 09:02:55

标签: image png jpeg nsdata

如果我得到NSData,我知道它是图像的数据。但我不知道它是什么格式。 那么如何识别它的图像格式呢?Jpeg还是PNG?

PS:iOS的

5 个答案:

答案 0 :(得分:16)

我使用Mats的答案在NSData上构建一个简单的类别,告诉我它的内容是基于前4个字节的JPEG或PNG:

@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

然后,只需做一个:

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);

答案 1 :(得分:8)

您可以查看第一个字节并进行猜测。互联网上有许多魔术数字列表,例如http://www.astro.keele.ac.uk/oldusers/rno/Computing/File_magic.html

答案 2 :(得分:1)

这是@ apouche的答案的Swift版本:

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
  }
}

答案 3 :(得分:0)

你可以从中创建一个图像,然后只询问NSImage它的格式是什么?

您可以使用-initWithData创建NSImage,有关详情,请参阅http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSImage_Class/Reference/Reference.html

答案 4 :(得分:0)

您可以创建CGImageSourceRef,然后询问它的图像类型

    CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef) imageData, NULL);

    if(imageSource)
    {
        // this is the type of image (e.g., public.jpeg - kUTTypeJPEG )
        // <MobileCoreServices/UTCoreTypes.h>

        CFStringRef UTI = CGImageSourceGetType(imageSource);

        CFRelease(imageSource);
    }

    imageSource = nil;