你可以採取以下方法
-(void) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
if ([[extension lowercaseString] isEqualToString:@"png"]) {
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]] options:NSAtomicWrite error:nil];
} else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"]) {
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]] options:NSAtomicWrite error:nil];
} else {
ALog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);
}
}
要保存圖像,簡單地做它是這樣的:
NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[self saveImage:yourImage withFileName:@"Your Image Name" ofType:@"png" inDirectory:path];
要加載圖像,實現此方法:
-(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.%@", directoryPath, fileName, extension]];
return result;
}
,然後用它是這樣的:
NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
yourImage.image = [self loadImage:@"Your Image Name" ofType:@"png" inDirectory:path];
或者你可以簡單地設置你的形象等於一下這個方法返回而不是創建一個方法:你檢查的`返回值
NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
yourImage.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/Your Image Name.png", path]];
將writeToFile:原子:'?如果出現錯誤,可以使用'writeToFile:options:error:'variant來檢查它是什麼。 – MrTJ 2012-03-30 10:38:23
另外,爲什麼你實際上需要將應用程序包中的圖像複製到文檔目錄中? – MrTJ 2012-03-30 10:39:33
你有沒有檢查你的設備代碼? 因爲模擬器不會逐行執行代碼.. [imageData writeToFile:fullPathToFile atomically:NO];方法花費一些時間將圖像寫入路徑,因此嘗試在一段時間後在圖像中加載圖像 – 2012-03-30 10:39:52