在UIImagePickerController中保存图像

时间:2013-09-17 19:06:11

标签: objective-c uiimagepickercontroller

我有一个关于如何在UIImagePickerController中保存图片的小问题。

我已尝试使用以下代码:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image didFinishPickingMediaWithInfo:(NSDictionary *)info {

if (takePhotoSave == 1) {
    takePhotoSave = 0;

    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    [picker dismissViewControllerAnimated:YES completion:NULL];
} }

我没有错误,但图片未保存

非常感谢

2 个答案:

答案 0 :(得分:0)

NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:NO completion:nil];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];

if (CFStringCompare ((__bridge_retained CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo){
        UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

        //save to document directory
        NSData *pngData = UIImagePNGRepresentation([self imageWithImage:image scaledToSize:CGSizeMake(image.size.width/5, image.size.height/5)]);
        NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image_test.png"]; //Add the file name
        [pngData writeToFile:filePath atomically:YES]; //Write the file


    }

这是保存到照片所需的一切。如果你想将它保存为下面的uiimage:

if ([NSData dataWithContentsOfFile:[self documentsPathForFileName:@"image_test.png"]]) {

    NSData* pngData = [NSData dataWithContentsOfFile:[self documentsPathForFileName:@"image_test.png"]];
    UIImage* image = [UIImage imageWithData:pngData];


    UIImageView* imageView = [[UIImageView alloc] initWithImage:image];
    [imageView setFrame:CGRectMake(0.0, 0.0, imageView.image.size.width, imageView.image.size.height)];
    [imageView setCenter:self.view.center];
    [self.view addSubview:imageView];

}

答案 1 :(得分:0)

这里的问题似乎是你没有设定完成目标。

UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);

这对我来说很有效,所以应该解决你的问题。

您还可以设置完成目标以检查其是否正确保存:

// Save image
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:), nil);

//检查是否有错误

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error {

    // Unable to save the image
    if (error) {

    }
    // All is well
    else {

    }
}

希望这有帮助