UIImage from file problem

I am trying to load a saved image, but when I check the UIImage, it returns as zero. Here is the code:

UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"/var/mobile/Applications/B74FDA2B-5B8C-40AC-863C-4030AA85534B/Documents/70.jpg" ofType:nil]]; 

Then I check img to see if it is nil and it. The directory listing shows the file, what am I doing wrong?

+7
source share
4 answers

You need to specify the "Documents" folder in your application, and then:

 - (NSString *)applicationDocumentsDirectory { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; return basePath; } 

Using:

 UIImage *img = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/70.jpg",[self applicationDocumentsDirectory]]]; 
+18
source

Firstly, you are using pathForResource incorrectly, the correct way:

 [[NSBundle mainBundle] pathForResource:@"70" ofType:@"jpg"] 

The whole idea of ​​linking is an abstract resource path, such as one that will always be valid, no matter where your application is on the system. But if all you want to do is upload an image that I would recommend using imageNamed: since it automatically processes the detection of retina display (high resolution) on the iPhone for you and downloads the corresponding resource “automatically”:

 UIImage *img = [UIImage imageNamed:@"70.jpg"]; 

To easily maintain regular resolution and retina resolution, you need to have two resources in your application suite: 70.jpg and 70@2x.jpg with the resource @ 2x doubled and height.

+7
source

Try loading UIImage with

 [UIImage imageNamed:@"something.png"] 

He searches for an image with the specified name in the main application suite. Also nice: it automatically selects the version of Retina ( xyz@2x.png ) or non-Retina (xyz.png).

+5
source

Your path simply does not work, because your application is in the sandbox, and you are trying to use the full path.

Instead, you should use the following:

UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"70" ofType:@"jpg"]];

or you can use, but slower than above:

UIImage *img = [UIImage imageNamed:@"70.jpg"];

+3
source

All Articles