Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get image width and height before loading it completely in iPhone

I am loading an image in my UITableViewCell using

[NSData dataWithContentsOfURL:imageUrl]

For setting custom height for my tableview cell , i need the actual size of the image that am loading.

Can we get the width and height of an image before loading it completely ? Thanks in advance.

like image 574
S.P. Avatar asked Jun 24 '11 13:06

S.P.


People also ask

How do I find my Uiimage size?

You can also right-click on an image & choose properties from the drop-down menu. A new window will appear with several tabs. You'll click the details tab, and there you'll find you image size and dimensions.

How do you fix the width and height of an image?

The height and width of an image can be set using height and width attribute. The height and width can be set in terms of pixels. The <img> height attribute is used to set the height of the image in pixels. The <img> width attribute is used to set the width of the image in pixels.


3 Answers

Try the Image I/O interface as done below. This will allow you to get the image size without having to load the entire file:

#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 147
Alex Avatar answered Oct 04 '22 10:10

Alex


you can do it like this:

NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
UIImage *image = [UIImage imageWithData:imageData];
NSLog(@"image height: %f",image.size.height);
NSLog(@"image width: %f",image.size.width); 
like image 23
Samuel Avatar answered Oct 04 '22 10:10

Samuel


Take a look at this Question How do I extract the width and height of a PNG from looking at the header in objective c which shares how is it possible to parse image Meta-data.

I have a created OpenSource project Ottran that extracts the image size and type of a remote image by downloading as little as possible, which supports PNG, JPEG , BMP and GIF formats.

like image 27
Bala Avatar answered Oct 04 '22 10:10

Bala