Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Image size from URL in ios

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.

like image 502
Muhammad Zeeshan Anwar Avatar asked May 24 '16 08:05

Muhammad Zeeshan Anwar


2 Answers

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"]);
like image 196
Alex Avatar answered Oct 04 '22 03:10

Alex


Swift 4.x
Xcode 12.x

func sizeOfImageAt(url: URL) -> CGSize? {
    // with CGImageSource we avoid loading the whole image into memory
    guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else {
        return nil
    }
    
    let propertiesOptions = [kCGImageSourceShouldCache: false] as CFDictionary
    guard let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, propertiesOptions) as? [CFString: Any] else {
        return nil
    }
    
    if let width = properties[kCGImagePropertyPixelWidth] as? CGFloat,
       let height = properties[kCGImagePropertyPixelHeight] as? CGFloat {
        return CGSize(width: width, height: height)
    } else {
        return nil
    }
}
like image 39
Abdul Karim Avatar answered Oct 04 '22 03:10

Abdul Karim