PDA

View Full Version : initWithContentsOfFile won't load image




GregX999
Apr 30, 2009, 08:20 PM
Hey, stupid newbie question here...

I'm trying to load an image from the Resources folder using initWithContentsOfFile. The code below always writes "Invalid Image" in the log. (And looking at the NSImage object in the debugger shows the "_name" as "Invalid".)

image = [[NSImage alloc] initWithContentsOfFile:@"player_ship.png"];

if (![image isValid]) {
NSLog(@"Invalid Image");
}

I copied that file into the Resources folder in xCode, and if "View Package Contents" of the build, it's in the Resources folder there too. It's just a png file I saved via Photoshop's "Save for Web" function.

Is there anyway I can figure out what the problem is?

Thanks,
Greg



kainjow
Apr 30, 2009, 08:37 PM
File paths in Cocoa must be absolute, and you're passing a relative path. To get the absolute path of a file in your app's Resources folder, you need to use the NSBundle class. Look at the docs, it should be fairly obvious.

lee1210
Apr 30, 2009, 08:56 PM
I would encourage looking this stuff up on your own as well, but since i already went to the trouble i figured i'd post what i found. You'll have to verify, i haven't tried compiling this or anything.

NSString *myImagePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"player_ship.png"];
NSImage *myImage = [[NSImage alloc] initWithContentsOfFile:myImagePath];


Relevant links:
NSBundle
http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSBundle_Class/Reference/Reference.html

NSString
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html

-Lee

GregX999
May 1, 2009, 07:49 AM
Thanks guys! I wasn't even aware of NSBundle. It would be kind of nice if the docs for initWithContentsOfFile at least mentioned it.

Lee, your code worked except for a missing "/". It needed to be:
stringByAppendingString:@"/player_ship.png"

Greg

lee1210
May 1, 2009, 08:44 AM
Ah, right. Might be better to use NSString's:
stringByAppendingPathComponent:

That will ensure the / is there:
NSString *myImagePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"player_ship.png"];

-Lee

kainjow
May 1, 2009, 11:38 AM
There's also the handy pathForImageResource: method when dealing with images.

reggoboy
Apr 14, 2011, 10:30 PM
Thanks guys! I wasn't even aware of NSBundle. It would be kind of nice if the docs for initWithContentsOfFile at least mentioned it.

Greg

Agreed!

But thanks for the tip about NSBundle.

Catfish_Man
Apr 15, 2011, 01:43 AM
There's also the handy pathForImageResource: method when dealing with images.

URLForImageResource in the modern world ;)

It has a number of advantages, including letting you change image formats without changing your code.