我知道有一些解决方案用于在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'看起来不错,不是? –