UIImage → NSData (存儲/傳輸)
UIImage *image = imageView.image;
// PNG 無損、透明
NSData *pngData = UIImagePNGRepresentation(image);
// JPEG 有損、體積小、無透明
NSData *jpegData = UIImageJPEGRepresentation(image, 0.8); // 0.0~1.0 壓縮質量
NSData → UIImage (讀取/顯示)
NSData *data = ...; // 從文件、網絡、數據庫讀取
UIImage *image = [UIImage imageWithData:data];
if (image) {
imageView.image = image;
} else {
NSLog(@"Data 非有效圖片格式或已損壞");
}
進階:文件落盤與緩存
// 寫入沙箱
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject
stringByAppendingPathComponent:@"avatar.png"];
[pngData writeToFile:path atomically:YES];
// 讀取
NSData *cachedData = [NSData dataWithContentsOfFile:path];
UIImage *cachedImage = [UIImage imageWithData:cachedData];
性能與內存建議
- 大圖 (>1MB) 建議用
imageWithData:scale: 指定屏幕縮放因子,避免解碼出過大位圖。
- 頻繁讀寫同一圖片時,優先使用
NSCache 或第三方庫 (SDWebImage/Kingfisher) 管理內存/磁盤二級緩存。
- 網絡下載圖片務必在子線程解碼 (
imageWithData: 耗時),主線程只賦值 imageView.image。