我有一个应用程序,允许用户从他们的相机胶卷中选择一张图片,并将其显示在UIImageView中。我通常使用这种方法在文本字段中保存文本,我认为它也适用于图像,但我遇到了一些问题。没有错误,但它根本不保存图像。
这是我正在使用的相关代码:
·H:
#define kFilename9 @"PGdata.plist"
...
- (NSString *)dataFilePath;
的.m:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename9];
}
- (void)applicationDidEnterBackground:(NSNotification *)notification {
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:image.image];
[array writeToFile:[self dataFilePath] atomically:YES];
}
- (void)viewDidLoad
{
...
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
image.image = [array objectAtIndex:0];
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:app];
[super viewDidLoad];
}
答案 0 :(得分:3)
您必须首先使用UImagePNGRepresentation或UIImageJPEGRepresentation将UIImage转换为PNG或JPG。这些函数返回NSData,然后您可以将其写入文件。
答案 1 :(得分:1)
您可以按照这种方式保存。
UIImage * image;//the image you want to save
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir=[paths objectAtIndex:0];
NSFileManager *filemanager=[NSFileManager defaultManager];
NSData * imagedata=UIImageJPEGRepresentation(image,1);
NSString *savePath= [docDir stringByAppendingPathComponent:@"imageName.jpg"];
BOOL isdic=NO;
BOOL isHave=[filemanager fileExistsAtPath:savePath isDirectory:&isdic];
if (isHave==YES&&isdic==NO) {
[filemanager removeItemAtPath:savePath error:nil];
}
BOOL result= [imagedata writeToFile:savePath atomically:YES];