views:

138

answers:

3

Why is this code setting artistImage to an image with 0 width and 0 height?

NSURL *artistImageURL = [NSURL URLWithString:@"http://userserve-ak.last.fm/serve/252/8581581.jpg"];
NSImage *artistImage = [[NSImage alloc] initWithContentsOfURL:artistImageURL];

A: 

Last I checked, NSImage's -initWithContentsOfURL: only works with file URLs. You'll need to retrieve the URL first, and then use -initWithData:

NSResponder
Also worth noting that it's never a good idea to use any of the `-initWithContentsOfURL:` methods from the main thread as they will block the main event loop. Use an asynchronous `NSURLConnection` object to create an `NSData` object and notify on completion instead.
Rob Keniger
NSImage can load from the network. Yes on Rob's point, though.
Ken
+1  A: 

NSImage does load this fine for me, but that particular image has corrupt metadata. Its resolution according to the exif data is 7.1999997999228071e-06 dpi.

NSImage respects the DPI info in the file, so if you try to draw the image at its natural size, you'll get something 2520000070 pixels across.

Ken
A: 

As Ken wrote, the DPI is messed up in this image. If you want to force NSImage to set the real image size (ignoring the DPI), use the method described at http://borkware.com/quickies/one?topic=NSImage:

NSBitmapImageRep *rep = [[image representations] objectAtIndex: 0];
NSSize size = NSMakeSize([rep pixelsWide], [rep pixelsHigh]);
[image setSize: size];
Psionides
This is not safe in general. That's an unsafe cast to NSBitmapImageRep. For example, an arbitrary image might be a PDF backed, in which case pixelsWide and pixelsHigh would return NSImageRepMatchesDevice indicating that the rep is resolution independent. NSImageRepMatchesDevice == 0.
Ken
That's good to know... but for standard web images (png, gif, jpg) this shouldn't happen, right?
Psionides