将图像保存到文档目录 - 不工作 - 仅创建零字节文件

时间:2012-10-31 18:26:49

标签: uiimage uiimagepickercontroller

我正在尝试创建一个简单的应用程序来拍照并将文件保存到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 个答案:

答案 0 :(得分: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];

此代码会将图像保存在文件夹中。

快乐编码.. !!!!!!