从iPhone的文档目录加载图像
问题描述:
我想从我的应用程序文档库中加载图像到UIImageView。我试图使用下面的代码,但它不工作。从iPhone的文档目录加载图像
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]];
有人可以帮助我这样做。谢谢...
答
我想你实际上需要的是:
UIImage *img = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"myimagefile" ofType:@"png"]];
[self.testView.imgView setImage:img];
+0
此解决方案有效 – 2014-01-14 09:21:11
答
使用[UIImage imageNamed:@"ThumbnailSmall.jpg"];
这将加载你想要什么,我认为。
答
如果你真的要加载从您的应用程序的文档文件夹中的图片,你可以这样做:
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];
答
斯威夫特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
}
为什么不使用imageNamed上的UIImage? – Grouchal 2009-06-20 06:34:45