在iOS设备上本地存储图像 [英] Storing images locally on an iOS device

查看:103
本文介绍了在iOS设备上本地存储图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

某些iOS照片相关应用程序会将应用程序创建的图像存储在照片库以外的其他位置。例如,Fat Booth显示了在app启动时使用该应用程序创建的滚动列表。请注意,这些照片会在用户明确将其保存到照片库时保留。 在iOS应用程序中保存和保存图像的最简单方法是什么?

Some iOS photo-related apps store images created with the app somewhere other than the photo library. For example Fat Booth shows a scrolling list of photos created with the app at app start-up. Note these photos are persisted w/o the user explicitly saving them to the photo library. What is the simplest way to save and persist images inside an iOS application?

我熟悉的唯一持久性商店是NSUserDefaults和钥匙链。但是我从来没有听说过这些用于存储大量数据的图像。现在我想知道核心数据是否是最简单的方法。

The only persistent stores I'm familiar with are NSUserDefaults and the key chain. However I've never heard of these used to store larger pieces of data such as an image. Now I'm wondering if Core Data is the easiest way.

推荐答案

最简单的方法是将其保存在应用程序的Documents目录中并使用NSUserDefaults保存路径,如下所示:

The simplest way is to save it in the app's Documents directory and save the path with NSUserDefaults like so:

NSData *imageData = UIImagePNGRepresentation(newImage);

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",@"cached"]];

NSLog(@"pre writing to file");
if (![imageData writeToFile:imagePath atomically:NO]) 
{
    NSLog(@"Failed to cache image data to disk");
}
else
{
    NSLog(@"the cachedImagedPath is %@",imagePath); 
}

然后将imagePath保存在NSUserDefaults的某些字典中,或者你想要的,然后检索它只需:

Then save the imagePath in some dictionary in NSUserDefaults or however you'd like, and then to retrieve it just do:

 NSString *theImagePath = [yourDictionary objectForKey:@"cachedImagePath"];
 UIImage *customImage = [UIImage imageWithContentsOfFile:theImagePath];

这篇关于在iOS设备上本地存储图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆