5

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

jrck
  • 119
  • 1
  • 2
  • 6
  • Are you sure the image is being copied into your bundle? – CodaFi Mar 24 '14 at 06:54
  • Yes. I see image in Supporting Files in Xcode and also in project folder in Finder. – jrck Mar 24 '14 at 07:37
  • 1
    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 Mar 24 '14 at 07:51

2 Answers2

12

Swift Style:

if let imageRef = NSImage(byReferencingFile: "/path/to/galaxy.jpg")
{
    print("image size \(imageRef.size.width):\(imageRef.size.height)")
}
Peter Kreinz
  • 7,979
  • 1
  • 64
  • 49
9

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

Buntylm
  • 7,345
  • 1
  • 31
  • 51