图片存到本地

来源:互联网 发布:网络提现 需要牌照 编辑:程序博客网 时间:2024/05/18 00:47
把图片缓存到本地,在很多场景都会用到,如果是只储存文字信息,那建一个plist文件,或者数据库就能很方便的解决问题,但是如果存图片到沙盒就没那么方便了。这里介绍两种保存图片到沙盒的方法。

一.把图片转为base64的字符串存到数据库中或者plist文件中,然后用到的时候再取出来

    //获取沙盒路径,    NSString *path_sandox = NSHomeDirectory();    //创建一个存储plist文件的路径    NSString *newPath = [path_sandox stringByAppendingPathComponent:@"/Documents/pic.plist"];    NSMutableArray *arr = [[NSMutableArray alloc] init];    //把图片转换为Base64的字符串    NSString *image64 = [self encodeToBase64String:image];    [arr addObject:image64];    //写入plist文件    if ([arr writeToFile:newPath atomically:YES]) {        NSLog(@"写入成功");    };

这样就存起来的,然后用到的时候再利用存储的字符串转化为图片

NSData *_decodedImageData   = [[NSData alloc] initWithBase64Encoding:image64];    UIImage *_decodedImage      = [UIImage imageWithData:_decodedImageData];

二.把图片直接保存到沙盒中,然后再把路径存储起来,等到用图片的时候先获取图片的路径,再通过路径拿到图片

//拿到图片UIImage *image = [UIImage imageNamed:@"flower.png"]; NSString *path_sandox = NSHomeDirectory();//设置一个图片的存储路径NSString *imagePath = [path_sandox stringByAppendingString:@"/Documents/flower.png"];//把图片直接保存到指定的路径(同时应该把图片的路径imagePath存起来,下次就可以直接用来取)[UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];

下次利用图片的地址直接来拿图片。
同时附上获取沙盒目录的代码
沙盒文件目录获取代码:

//Home目录

NSString *homeDirectory = NSHomeDirectory();

//Document目录

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

//Cache目录

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

//Libaray目录

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


0 0