Search code examples
objective-cimagemacosnsdata

How can I extract image information dumped in NSData


I have as an input the dump of an image in an NSData object. Now, I want to extract relevant information of the image from this object like number of pixels, no. of bits per pixel, etc.

Can anyone tell me how to extract this info from the NSData object dump?

P.S.: I have gone through this documentation of the NSData class, but could not isolate out the relevant methods.


Solution

  • So the easiest way is to actually build the UIImage object from the NSData then extract the info from the UIImage then.

    UIImage* image = [UIImage imageWithData:yourData];
    NSLog(@"Image is %dx%d",image.size.width, image.size.height);
    

    If you are only interested in the properties of the image but don't want to actually build its representation and only get the properties, take a look at CGImageSource

    #import <ImageIO/ImageIO.h>
    
    CGImageSourceRef imgSrc = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    size_t nbImages = CGImageSourceGetCount(imgSrc);
    for(size_t idx=0; idx<nbImages; ++idx)
    {
        NSDictionary* props = (__bridge NSDictionary*)CGImageSourceCopyPropertiesAtIndex(imgSrc, idx, NULL);
        NSLog(@"properties for image %lu in imageSource: %@", idx, props);
    }
    CFRelease(imgSrc);
    

    [EDIT] For this to work, obviously add the ImageIO.framework to your "Link Binary With Libraries" How to add ImageIO framework