【问题标题】:How to Fetch image from specified PATH or Document Directory using NSBundle如何使用 NSBundle 从指定的 PATH 或文档目录中获取图像
【发布时间】:2013-09-02 12:21:14
【问题描述】:

我做了很多研究来找出以下代码的工作方式之间的区别。 当我试图从 PATH 使用 NSBundle 指定的文档目录中获取图像并将其显示在 ImageView 中时。

类型 1: 此代码工作正常,能够检索图像并显示:

NSString *inputPath= @"/Users/abc/Library/Application Support/iPhone Simulator/6.0/Applications/ADD46F96-333A-46BF-8291-FABD1BD7C389/Documents/colour.png";
NSString *jjj=[inputPath pathExtension];
NSString *hhhhh=[[inputPath lastPathComponent]stringByDeletingPathExtension];
NSString *bivivik=[inputPath stringByDeletingLastPathComponent];
NSString *imagePATH=[NSBundle pathForResource:hhhhh ofType:jjj inDirectory:bivivik];
theImage=[UIImage imageWithContentsOfFile:imagePATH];
mImageDisplayView.image=theImage;

类型 2: 但是如果我尝试如下代码。不获取图像并显示空值

NSString* imagepath = [[NSBundle bundleWithPath:@"/Users/abc/Library/Application Support/iPhone Simulator/6.0/Applications/ADD46F96-333A-46BF-8291-FABD1BD7C389/Documents/colour.png"]bundlePath];
theImage=[UIImage imageWithContentsOfFile:imagepath];
mImageDisplayView.image=theImage;

我的 TYPE 2 代码有什么问题。有没有其他方法可以像我在 TYPE 2 方法中尝试的那样获取图像。请帮助我

【问题讨论】:

    标签: ios objective-c ios5 nsbundle


    【解决方案1】:

    尽管上面的代码在一个实例中有效,但两个代码 sn-ps 都是错误的,因为它们无法读取设备上的文件。原因是,您正在使用模拟器能够找到的 MAC 中的绝对路径,但在设备上不存在。

    使用[NSBundle mainBundle] 从应用程序包中读取文件,

    [[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"png"];
    

    要从应用程序的文档目录中读取文件,请使用此代码 sn-p,

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Myfile.png"];
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
    

    编辑

    如果您有一个包含图像文件的单独包,那么要从该包中读取,请使用这个 sn-p。假设这个包在文档目录中,

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *bundlePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"MyBundle.bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:bundlePath];
    NSString* imagePath = [myBundle pathForResource:@"MyImage" ofType:@"png"];
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:imagePath];
    

    希望有帮助!

    【讨论】:

    • 你的回答被接受了。如果我需要使用 NSBundle 访问图像怎么办? ca 我像这样使用 filePath NSString* imagepath = [[NSBundle bundleWithPath:filePath]bundlePath]; 它会工作吗?
    • @lok​​esh 忽略我之前的评论。上述 API 不用于获取应用程序包中的文件。它用于获取 .bundle 文件的路径。
    • 您是否从mainBundle以外的单独包中读取图像文件?
    • 是的,我需要使用 bundle 从文档目录中读取图像
    • @lok​​esh 如果我没弄错,您想从存储在 Documents 目录中的包中读取文件吗?
    猜你喜欢
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    相关资源
    最近更新 更多