2012-10-31 70 views
0

我正在嘗試製作一個簡單的應用程序來拍攝圖片並將該文件保存到UIImageview和文檔文件夾中,以便可以在稍後作爲UIImageview。要了解應用程序是否實際製作文件,我已打開應用程序支持.plist文件中的iTunes文件共享。將圖像保存到文檔目錄 - 不工作 - 僅創建零字節文件

問題是生成的文件是零字節。我已經嘗試了PNG和JPG格式。

- (IBAction)picImage:(id)sender { 
imagePicker = [[UIImagePickerController alloc] init]; 
imagePicker.delegate = self; 

//check to see if the device has camera capability 
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) 
{ 
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; 

} 
else 
{ 
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 
} 

[self presentViewController:imagePicker animated:YES completion:nil]; 
} 

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{ 
    //set the UIImageView to the selected image 
    playerImage.image = [info objectForKey:UIImagePickerControllerOriginalImage]; 

    //obtaining saving path 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:@"player.png"]; 

    UIImage *editedImage = [UIImage imageWithContentsOfFile:imagePath]; 
    NSData *imageData = UIImagePNGRepresentation(editedImage); 
    //NSData *imageData = UIImageJPEGRepresentation(editedImage,1.0); 

    // This actually creates the image at the file path specified, with the image's NSData. 
    [[NSFileManager defaultManager] createFileAtPath:imagePath contents:imageData attributes:nil]; 

    //dismiss the imagepicker view controller 
    [self dismissViewControllerAnimated:YES completion:nil]; 
} 

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker 
{ 
[self dismissViewControllerAnimated:YES completion:nil]; 
} 

回答

1

試試這個代碼,讓我知道是它的工作或不.. !!!!

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *strimagename; 
    strimagename=[NSString stringWithFormat:@"Test.jpg"]; 


NSString *thumbFilePath = [documentsDirectory stringByAppendingPathComponent:strimagename]; 
UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"]; 
NSData *thumbData = UIImageJPEGRepresentation(image, 1); 
[thumbData writeToFile:thumbFilePath atomically:YES]; 
[imgPicker dismissModalViewControllerAnimated:YES]; 

此代碼將圖像保存在文件夾documentory ..

編碼愉快.. !!!!!!

+0

謝謝!這對最後一行進行了兩處小修改。我必須將imgPicker更改爲self,並將已棄用的dismissModal ...函數更改爲已更新的函數。 - [self dismissViewControllerAnimated:YES completion:nil]; – jdeason

+0

偉大的工作..... !!!! – NiravPatel