alexyorke
alexyorke

Reputation: 4299

Dimensions of image objective-c

I would like to know how to retrieve the dimensions of an image with objective-c. I have searched google and the documentation with no success, unfortunately.

Upvotes: 1

Views: 4565

Answers (4)

daniel.gindi
daniel.gindi

Reputation: 3496

You could use the NSString+FastImageSize category from the Additions section in https://github.com/danielgindi/drunken-danger-zone

I've only recently written it, and it seems to work fine.

This code will actually open the file and check the headers for dimensions (= it is really really fast), and supports PNG,JPG,GIF and BMP. Although I really hope you don't use BMP on a mobile device...

Enjoy!

Upvotes: 0

Jens Ayton
Jens Ayton

Reputation: 14558

The size method is correct for a size in points. Sometimes you need the pixel dimensions rather than the nominal size, in which case you must select an image rep (NSImages can have several) and query its pixelsWide and pixelsHigh properties. (Alternatively, load images using CGImage and use CGImageGetWidth() and CGImageGetHeight().

Upvotes: 0

dreamlax
dreamlax

Reputation: 95335

NSImage has a size method, returning an NSSize struct containing the width and height of the image, or {0, 0} if the size couldn't be determined.

NSImage *image = [NSImage imageNamed:@"myimage.png"];

NSSize dimensions = [image size];

NSLog (@"Width: %lf, height: %lf", (double) dimensions.width, (double) dimensions.height);

Edit:

I have placed explicit casts to double because on some systems (64-bit especially) the width and height members may not be float types but double, and we would be providing the wrong types to NSLog. A double can represent more values than float, so we can cast up with a bit more safety.

Upvotes: 9

Simon Whitaker
Simon Whitaker

Reputation: 20566

In iOS, UIImage has a size property, which returns a CGSize.

In OS X, NSImage has a size method which returns an NSSize. It also has a representations property, which returns an NSArray of NSImageRep objects. NSImageRep has a size method.

Upvotes: 6

Related Questions