zoukankan      html  css  js  c++  java
  • IOS把图片缓存到本地的几种方法

    把图片缓存到本地,在很多场景都会用到,如果是只储存文字信息,那建一个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];
  • 相关阅读:
    14.3.3.2 Configuring the Rate of InnoDB Buffer Pool Flushing 配置 InnoDB Buffer Pool 刷新频率
    14.3.3 InnoDB Buffer Pool Configuration InnoDB Buffer Pool 配置:
    Perl 中的对象
    MyCat不支持的SQL语句
    第6章 模块
    Linux_RAID
    mysql limit
    svn 备份和恢复
    农商行信息化建设过程中存在哪些问题?
    14.2.6.4 Physical Structure of an InnoDB Index InnoDB Index 物理结构
  • 原文地址:https://www.cnblogs.com/sunfuyou/p/6141620.html
Copyright © 2011-2022 走看看