繁体   English   中英

从文档目录加载图像

[英]Loading an Image from documents directory

我无法显示我的图像(.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

我尝试了其他几种方法,但没有出现任何方法。

尝试使用

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

您应该使用[NSURL fileURLWithPath:imgPath]而不是[NSURL URLWithString:imgPath] 图像路径不是有效的URL,它需要file://前缀。

您需要提供适当的文件URL

NSURL *imgURL = [NSURL fileURLWithPath:imgPath];

然后使用适当的imgURL var初始化您的图像,最后将图像添加到您需要执行以下操作的单元格中

[cell.contentView addSubview:imgView];

我希望它可以解决你的问题。

imageView.image = [UIImage imageWithContentsOfFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"Filename"]];

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

你的网址很完美。

您需要使用以下行初始化图像

UIImage *thumbNail=[UIImage imageWithContentsOfFile:imagePath];

现在这样做

[imgView setImage:thumbNail];

[cell addSubview:imgView];

暂无
暂无

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

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