我无法显示我的图像(.png)。
我检查它是否存在于我使用的路径中,它确实存在。但是没有图像出现。
以下是我一直在尝试的内容:
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];
确认文件存在的调试输出
FOUND IMG
2011-12-26 12:42:23.066 iGeo2[412:707] /var/mobile/Applications/1A2B0D85-CDB1-4E4B-
9509-EF68B1A0E720/Documents/0.009000.png
我有点困惑。有谁看到我犯了错误?
非常感谢, -code
我尝试了其他几种方法,但没有出现任何方法。
答案 0 :(得分:21)
尝试使用
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];
答案 1 :(得分:17)
您应该使用[NSURL fileURLWithPath:imgPath]
代替[NSURL URLWithString:imgPath]
。图片路径不是有效网址,需要file://
前缀。
答案 2 :(得分:4)
您需要提供适当的文件网址
NSURL *imgURL = [NSURL fileURLWithPath:imgPath];
然后使用适当的imgURL var初始化您的图像,最后将图像添加到您需要执行以下操作的单元格
[cell.contentView addSubview:imgView];
我希望它可以解决你的问题。
答案 3 :(得分:3)
imageView.image = [UIImage imageWithContentsOfFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"Filename"]];
答案 4 :(得分:1)
Swift 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")
答案 5 :(得分:0)
你的网址很完美。
您需要使用以下行
初始化图像UIImage *thumbNail=[UIImage imageWithContentsOfFile:imagePath];
现在这样做
[imgView setImage:thumbNail];
[cell addSubview:imgView];