繁体   English   中英

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

[英]loading a image from documents directory in 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]];

有人可以帮助我这样做。 谢谢...

如果您真的想从应用程序的文档文件夹中加载图像,可以使用:

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

请参阅此相关问题 ,其中包含您需要的代码。

我认为你真正需要的是:

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

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

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

这将加载你想要的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM