How to get Image size from URL in ios

Muhammad Zeeshan Anwar picture Muhammad Zeeshan Anwar · May 24, 2016 · Viewed 8.1k times · Source

How can I get the size(height/width) of an image from URL in objective-C? I want my container size according to the image. I am using AFNetworking 3.0. I could use SDWebImage if it fulfills my requirement.

Answer

Alex picture Alex · Oct 15, 2016

Knowing the size of an image before actually loading it can be necessary in a number of cases. For example, setting the height of a tableView cell in the heightForRowAtIndexPath method while loading the actual image later in the cellForRowAtIndexPath (this is a very frequent catch 22).

One simple way to do it, is to read the image header from the server URL using the Image I/O interface:

#import <ImageIO/ImageIO.h>

NSMutableString *imageURL = [NSMutableString stringWithFormat:@"http://www.myimageurl.com/image.png"];

CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)[NSURL URLWithString:imageURL], NULL);
NSDictionary* imageHeader = (__bridge NSDictionary*) CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
NSLog(@"Image header %@",imageHeader);
NSLog(@"PixelHeight %@",[imageHeader objectForKey:@"PixelHeight"]);