ios 如何从 UIImage 获取文件路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20251250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the file path from a UIImage?
提问by Mirror318
Usually it's the other way around, you use the path to display the image. I was wondering if you can get the path if you already have the image.
通常情况相反,您使用路径来显示图像。我想知道如果您已经拥有图像,是否可以获得路径。
回答by Joel Balmer
if you already have the image i.e. have added the file to your resources, you can use this to get the file path;
如果您已经拥有图像,即已将文件添加到您的资源中,您可以使用它来获取文件路径;
NSString *string = [[NSBundle mainBundle] pathForResource:@"IMAGE_FILE_NAME" ofType:@"jpg"]; // or ofType:@"png", etc.
回答by Brianjs
I don't believe it is possible to get it directly from UIImage.
我不相信可以直接从 UIImage 获取它。
Best way is to save the image in a directory, then you will have the file path.
最好的方法是将图像保存在一个目录中,然后您将拥有文件路径。
//image is your UIImage;
if (image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
@"test.png" ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
path
will be your filepath.
path
将是您的文件路径。
回答by Holly
Once a UIImage is created, the image data is loaded into memory and no longer connected to the file on disk. As such, the file can be deleted or modified without consequence to the UIImage and there is no way of getting the source path from a UIImage.
创建 UIImage 后,图像数据将加载到内存中,不再连接到磁盘上的文件。因此,可以删除或修改文件而不会对 UIImage 产生影响,并且无法从 UIImage 获取源路径。