3
votes

I program command-line application that will load image from Supporting Files. Image is copied in Supporting Files, but when I use following code, variable imgC returns nil.

NSString* pathC = @"galaxy.jpg";
NSImage* imgC = [NSImage imageNamed: pathC];

ImgC returns nil even if I use the following code:

NSString* pathC = @"galaxy.jpg";
NSImage* imgC = [[NSImage alloc] initWithContentsOfFile: pathC];

Can someone please help me?

(PS: Sorry for my bad English.)

Many thanks, Peter

2
Are you sure the image is being copied into your bundle?CodaFi
Yes. I see image in Supporting Files in Xcode and also in project folder in Finder.jrck
The imageNamed: method only works in an application bundle, you can't use it from a command line tool. And initWithContentsOfFile: should be used with an absolute path, not a relative path. Also... you should be using URLs not paths.Abhi Beckert

2 Answers

10
votes

Swift Style:

if let imageRef = NSImage(byReferencingFile: "/path/to/galaxy.jpg")
{
    print("image size \(imageRef.size.width):\(imageRef.size.height)")
}
8
votes

As the target is commend line tool since those don't have a bundle [NSBundle mainBundle] so its returns nil. So You need to used an absolute path, not an relative path. As this is Strange Xcode do't show any kind of warning regarding to this.

NSImage *image = [[NSImage alloc]initWithContentsOfFile:@"/Users/Zenga/Documents/iOS/Research/Test/star.png"];
if (image == nil) {
    NSLog(@"image nil");
}
NSLog(@"%f and %f",image.size.width, image.size.height);

and i found this path from When i click on the Image and on Right Corner i found this path and i used it and working fine for me.

enter image description here