IOS把圖片緩衝到本地的幾種方法

來源:互聯網
上載者:User

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

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.