我知道有一些解决方案可以在iPhone上保存和加载图像。但是没有一个对我有用。
例如,下面的链接有一个很棒的代码块,可以让你用一个唯一的密钥加载和保存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];
}
如果你可以帮我解决这个问题,那将非常感激。我需要保存多个图像,并根据给定的密钥是否已存在加载它们。
答案 0 :(得分:2)
如果您想获取具有唯一键的图像,请尝试使用UUID。这将始终为您提供具有唯一键的图像。例如,这里是使用UUID的示例..
- (NSString *)pathForImageFileWithPrefix:(NSString *)Prefix
{
CFUUIDRef uuid;
CFStringRef uuidStr;
uuid = CFUUIDCreate(NULL);
uuidStr = CFUUIDCreateString(NULL, uuid);
NSData *imageData = UIImageJPEGRepresentation(chosenImage, 1.0);
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
result = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%@.png",Prefix, uuidStr]];
[imageData writeToFile:result atomically:NO];
CFRelease(uuidStr);
CFRelease(uuid);
return result;
}
答案 1 :(得分:0)
如果我的问题正确,您想知道具有给定图像名称的文件是否已存在?然后你可以使用
bool fileExists = [NSFileManager defaultManager] fileExistsAtPath:filePath];