gpt4 book ai didi

ios - 如何使用 NSBundle 从指定的路径或文档目录中获取图像

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:45:58 25 4
gpt4 key购买 nike

我做了很多研究来找出下面代码的工作方式之间的区别。当我试图从 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 方法时获取图像。请帮助我

最佳答案

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

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

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

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

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

编辑

如果您有一个包含图像文件的单独包,则使用此代码段从该包中读取。假设这个包在文档目录中,

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

希望对您有所帮助!

关于ios - 如何使用 NSBundle 从指定的路径或文档目录中获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18573163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com