我知道有一些解決方案用於在iPhone上保存和加載圖像。然而,沒有人爲我工作。iPhone使用唯一密鑰加載並保存多個UIImages?
例如,下面的鏈接有大的代碼塊,它可以讓您加載和保存一個UIImage了一個獨特的密鑰,但我不能工作了如何加載使用此代碼的圖像時告訴我們,如果根據該圖像密鑰已經存在或沒有。
//saving an image
- (void)saveImage:(UIImage*)image:(NSString*)imageName {
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
NSLog(@"image saved");
}
//removing an image
- (void)removeImage:(NSString*)fileName {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", fileName]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(@"image removed");
}
//loading an image
- (UIImage*)loadImage:(NSString*)imageName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]];
return [UIImage imageWithContentsOfFile:fullPath];
}
如果你能幫助我制定出了這將是非常讚賞。我需要保存多個圖像,並根據給定鍵是否已存在來加載它們。
我已經在loadImage方法中完成了我原來的文章。所以我有你的代碼行與保存的圖像的文件路徑,然後有一個if語句,所以如果'fileExists'它將返回該保存的圖像,否則它將返回零。然而,布爾似乎總是虛假的,我總是得到零回報。有關如何調整loadImage方法以檢查圖像是否存在的任何想法? –
你的文件路徑是怎樣的?你確定它是正確的,包括完整的目錄路徑,文件名和文件擴展名? – TheEye
我NSLogged它並得到這個:'/ var/mobile/Applications/42C18ABE-18B2-41C5-9389-BC5C15BD8BD4/Documents/imgSaved.png'看起來不錯,不是? –