2012-03-27 61 views
0

我有一個應用程序,允許用戶從他們的相機卷中選擇一張圖片,並將其顯示在UIImageView中。我通常使用這種方法來保存文本字段中的文本,並且我認爲它也適用於圖像,但我遇到了一些問題。沒有錯誤,但它不會保存圖像。iOS:在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]; 

} 

回答

3

你必須在第一的UIImage轉換成PNG或JPG ,使用UImagePNGRepresentation或UIImageJPEGRepresentation。那些函數返回你可以寫入文件的NSData。

+0

真棒非常感謝你。 – John 2012-03-27 19:49:25

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];