从文档目录加载图像
我不能让我的图像(.png)显示。
我检查它存在于我使用的path,它确实存在。 但是没有图像出现。
这是我一直在尝试的:
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; NSString *outputPath = [documentsDir stringByAppendingPathComponent:[fileList objectAtIndex:indexPath.row]]; NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease]; NSString *imgPath = [[outputPath stringByReplacingOccurrencesOfString:@"mov" withString:@"png"]retain]; if ([fileManager fileExistsAtPath:imgPath]) { NSLog(@"FOUND IMG"); NSLog(imgPath); } NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imgPath]]; UIImage *thumbNail = [[UIImage alloc] initWithData:imgData]; UIImageView * imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 120, 120)]; [imgView setImage:thumbNail]; [cell addSubview:imgView]; [imgView release];
确认文件的debugging输出存在
FOUND IMG 2011-12-26 12:42:23.066 iGeo2[412:707] /var/mobile/Applications/1A2B0D85-CDB1-4E4B- 9509-EF68B1A0E720/Documents/0.009000.png
我有点困惑。 有人看到我犯了错误吗?
非常感谢,代码
我已经尝试了一些其他的方法,但没有出现过。
你应该使用[NSURL fileURLWithPath:imgPath]
而不是[NSURL URLWithString:imgPath]
。 图片path不是一个有效的url,它需要一个file://
前缀。
尝试使用
NSData *imgData = [NSData dataWithContentsOfFile:imgPath]; UIImage *thumbNail = [[UIImage alloc] initWithData:imgData];
要么
NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:imgPath]]; UIImage *thumbNail = [[UIImage alloc] initWithData:imgData];
你需要给正确的文件的URL将是
NSURL *imgURL = [NSURL fileURLWithPath:imgPath];
然后使用适当的imgURL var初始化图像,最后将图像添加到您的单元格中,您需要执行以下操作
[cell.contentView addSubview:imgView];
我希望这可以解决你的问题。
imageView.image = [UIImage imageWithContentsOfFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"Filename"]];
你的url是完美的。
你需要用下面一行初始化图像
UIImage *thumbNail=[UIImage imageWithContentsOfFile:imagePath];
现在做这个
[imgView setImage:thumbNail]; [cell addSubview:imgView];
斯威夫特4
码:
extension FileManager { class func getImage(named: String) -> UIImage? { let imagePath = getImagePath(named: named) return UIImage(contentsOfFile: imagePath) } class func getImagePath(named: String) -> String { let fileManager = FileManager.default let documentDir = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) return documentDir.appendingPathComponent(named).path } }
用法:
let image = FileManager.getImage(named: "image.png")