Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage from file problem

I am trying to load an saved image but when I check the UIImage it comes back as nil. Here is the code:

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

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

like image 777
Phil Avatar asked Apr 27 '11 22:04

Phil


3 Answers

Your path simply wont work because your app is in a sandbox, and you are trying to use the full path.

You should be using the following instead:

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

or you can use, but is slower than the above:

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

like image 136
WrightsCS Avatar answered Nov 18 '22 12:11

WrightsCS


First, you are using pathForResource wrong, the correct way would be:

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

The whole idea of bundling is to abstract the resource path such as that it will always be valid, no matter where in the system your app resides. But if all you want to do is load that image I would recommend you use imageNamed: since it automatically handles retina resolution (high resolution) display detection on the iPhone for you and loads the appropriate resource "automagically":

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

To easily support regular and retina resolution you would need to have two resources in your app bundle, 70.jpg and [email protected] with the @2x resource having both doubled with and height.

like image 30
Robin Avatar answered Nov 18 '22 12:11

Robin


Try loading a UIImage with:

[UIImage imageNamed:@"something.png"]

It looks for an image with the specified name in the application’s main bundle. Also nice: It automatically chooses the Retina ([email protected]) or non-Retina (xyz.png) version.

like image 6
Julian Avatar answered Nov 18 '22 10:11

Julian