从iPhone中的文档目录加载图像

时间:2009-06-20 04:30:50

标签: iphone

我想从我的应用文档库中将图像加载到UIImageView。我试图使用以下代码,但它无法正常工作。

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]];

有人可以帮我做这件事。感谢...

6 个答案:

答案 0 :(得分:26)

如果确实想要从应用的文档文件夹中加载图片,可以使用:

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];

但是,正如其他人所指出的那样,您可能希望从应用包中加载它,在这种情况下,其中任何一个都可以使用:

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

NSString *path = [[NSBundle mainBundle] pathForResource:@"Thumbnail-small" ofType:@"jpg"];
background.image = [UIImage imageWithContentsOfFile:path];

答案 1 :(得分: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];

答案 2 :(得分:2)

请参阅包含所需代码的this related question

答案 3 :(得分:0)

我认为你真正需要的是:

UIImage *img = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"myimagefile" ofType:@"png"]];
[self.testView.imgView setImage:img];

答案 4 :(得分:0)

斯威夫特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
}

答案 5 :(得分:-4)

使用[UIImage imageNamed:@"ThumbnailSmall.jpg"];

这会加载你想要的东西。