10

I want to load a image to UIImageView from my app documents library. I am trying to use the following code but it is not working.

UIImageView *background = [[[UIImageView alloc] initWithFrame:CGRectMake(3, 10, 48, 36)] autorelease];

[background setImage:[[UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"Thumbnail-small" ofType:@"jpg" inDirectory:@"/Users/nbojja/Library/Application Support/iPhone Simulator/User/Applications/60C2E4EC-2FE0-4579-9F86-08CCF078216D/Documents/eb43ac64-8807-4250-8349-4b1f5ddd7d0d/9286371c-564f-40b4-99bd-a2aceb00a6d3/9"]]] retain]];

can someone help me with doing this. thanks...

nbojja
  • 1,665
  • 7
  • 28
  • 38

6 Answers6

25

If you really want to load an image from your app's documents folder, you could use this:

NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/Thumbnail-small.jpg", docDirectory];
background.image = [[[UIImage alloc] initWithContentsOfFile:filePath] autorelease];

However, as pointed out by others here, you probably want to load it from your app bundle, in which case either of these will work:

background.image = [UIImage imageNamed:@"Thumbnail-small.jpg"];

or

NSString *path = [[NSBundle mainBundle] pathForResource:@"Thumbnail-small" ofType:@"jpg"];
background.image = [UIImage imageWithContentsOfFile:path];
zpasternack
  • 17,838
  • 2
  • 63
  • 81
4
NSString *docPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath=[NSString stringWithFormat:@"%@/image.png",docPath];

BOOL fileExists=[[NSFileManager defaultManager] fileExistsAtPath:filePath];

if (!fileExists)
    NSLog(@"File Not Found");
else
    image = [UIImage imageWithContentsOfFile:filePath];
Mohit
  • 3,708
  • 2
  • 27
  • 30
2

See this related question which has the code you want.

Community
  • 1
  • 1
Rog
  • 17,070
  • 9
  • 50
  • 73
0

I think what you actually need is:

UIImage *img = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"myimagefile" ofType:@"png"]];
[self.testView.imgView setImage:img];
Alex Taylor
  • 7,128
  • 2
  • 26
  • 22
0

Swift 3:

let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first {
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("Image2.png")
let image = UIImage(contentsOfFile: imageURL.path)
// Do whatever you want with the image
}
oskarko
  • 3,382
  • 1
  • 26
  • 26
-4

Use [UIImage imageNamed:@"ThumbnailSmall.jpg"];

This will load up what you want I think.

Baby Groot
  • 4,637
  • 39
  • 52
  • 71
Grouchal
  • 9,756
  • 6
  • 34
  • 46