iOS開發-緩衝圖片到沙箱

來源:互聯網
上載者:User

今天寫一個demo, 涉及圖片快取作業。

也就是, 把通過照相機拍下來的圖片, 儲存到應用中。

因為還涉及了其他資料, 包括圖片像素大小, 關鍵點等等等...

所以很自然的想到了儲存在.plist檔案中, 再把plist檔案寫入沙箱。


於是乎..第一次寫的時候, 直接這樣:

NSString *documentsDirectory = [paths objectAtIndex:0];    NSString * namePath = [documentsDirectory stringByAppendingPathComponent:@"gift_info.plist"];        NSMutableArray *myArr = [[NSMutableArray alloc] initWithContentsOfFile:namePath];    NSMutableDictionary *info = [[NSMutableDictionary alloc]init];        [info setObject:myImage forKey:@"img"];    [myArr addObject:info];    [myArr writeToFile:namePath atomically:YES];

這裡的myImage就是我要儲存的UIImage類型的資料。

但是結果呢。很明顯, 這樣是儲存不了的(也就是不會產生對應的plist檔案)。因為plist檔案不能儲存UIImage類型的資料。

犯了這個低級錯誤...真是蛋疼。


然後接下去是第二版。

    [info setObject:UIImagePNGRepresentation(myImage)forKey:@"img"];

這裡修改了圖片的儲存類型:轉為NSData格式。

然後在要使用圖片的時候, 使用如下語句:

    UIImage *myImg = [UIImage imageWithData:[myArr objectAtIndex:i]objectForKey:@"img"];

這種辦法, 理論上行得通。

但是,  轉為data導致plist檔案過大,載入緩慢,影響其他資料的展示。所以也不是一個好辦法。


下面介紹我最後使用的一個辦法。

先把圖片直接儲存到沙箱中。 然後plist檔案中記錄圖片的路徑。然後要使用圖片的時候通過訪問plist檔案擷取圖片路徑來調用。

下面是使用樣本:

一。圖片儲存到沙箱中

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%d.png", myI]];   // 儲存檔案的名稱        [UIImagePNGRepresentation(myImage)writeToFile: filePath    atomically:YES];

二。在plist中儲存路徑

NSMutableDictionary *info = [[NSMutableDictionary alloc]init];NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%d.png", conut_]];   // 儲存檔案的名稱[info setObject:filePath forKey:@"img"];[specialArr addObject:info];

三。使用圖片

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%d.png", (int)current]];   // 儲存檔案的名稱UIImage *img = [UIImage imageWithContentsOfFile:filePath];


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.