How to get Image size from URL in ios
Asked Answered
T

5

6

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.

Tithonus answered 24/5, 2016 at 8:41 Comment(5)
Download the image before setting-up the view?Outnumber
There aren't any need to know size of image.Try to create UIImageView any size you want and change his content type(scaletofill, aspectfill, aspectfit etc)Fancywork
From which URL you download the image? Many API for image service provide the height/width property in the fetched data(like json) You can have the look at the API Document.Darbydarce
What a requirement!! Please verify your requirement once again. I guess you are missing something.Clippard
Thanks to all above. Actually image is coming from my own server. But These are not of the same resolutions. Minimum is 800*800. But I need to know image size to update my image view accordingly.Tithonus
D
19

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"]);
Developer answered 15/10, 2016 at 18:36 Comment(1)
Great answer! Helped me a lot. Thank you!Unthrone
B
6

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
    }
}
Bernicebernie answered 7/1, 2021 at 10:42 Comment(0)
A
3

Use Asynchronous mechanism called GCD in iOS to dowload image without affecting your main thread.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    // Download IMAGE using URL
    NSData *data = [[NSData alloc]initWithContentsOfURL:URL];

    // COMPOSE IMAGE FROM NSData
    UIImage *image = [[UIImage alloc]initWithData:data];

    dispatch_async(dispatch_get_main_queue(), ^{
        // UI UPDATION ON MAIN THREAD
        // Calcualte height & width of image
        CGFloat height = image.size.height;
        CGFloat width = image.size.width;

    });
});
Ambi answered 24/5, 2016 at 13:32 Comment(1)
I am not downloading actually. I am using AFNetworking cachying like [imageView setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:object] placeholderImage:[UIImage imageNamed:@"DefaultProductImage"]];Tithonus
G
1

For Swift 4 use this:

let imageURL = URL(string: post.imageBigPath)!
let source = CGImageSourceCreateWithURL(imageURL as CFURL,     
let imageHeader = CGImageSourceCopyPropertiesAtIndex(source!, 0, nil)! as NSDictionary;
print("Image header: \(imageHeader)")

The header would looks like:

Image header: { ColorModel = RGB; Depth = 8; PixelHeight = 640; PixelWidth = 640; "{Exif}" = { PixelXDimension = 360; PixelYDimension = 360; }; "{JFIF}" = { DensityUnit = 0; JFIFVersion = ( 1, 0, 1 ); XDensity = 72; YDensity = 72; }; "{TIFF}" = { Orientation = 0; }; }

So u can get from it the Width, Height.

Grater answered 13/7, 2018 at 12:25 Comment(0)
E
0

you can try like this:

NSData *data = [[NSData alloc]initWithContentsOfURL:URL]; 
UIImage *image = [[UIImage alloc]initWithData:data];
CGFloat height = image.size.height;
CGFloat width = image.size.width;
Electron answered 24/5, 2016 at 9:29 Comment(1)
This is a synchronous way. It will stuck the UI until it gets the data.Tithonus

© 2022 - 2025 — McMap. All rights reserved.