开发者

UIImagePickerController - save selected images

开发者 https://www.devze.com 2023-01-14 11:20 出处:网络
I\'m trying to save a selected image to a directory. My code is as follows: -(IBAction)attachPhotosButto开发者_如何学运维n

I'm trying to save a selected image to a directory. My code is as follows:

-(IBAction)attachPhotosButto开发者_如何学运维n
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 

    [self presentModalViewController:imagePicker animated:YES];

    // If image is selected, then save
        //[self saveImage];
    // else do nothing
}


-(void)saveImage 
{
    // This creates a string with the path to the app's Documents Directory.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    // Here we are calling the method we created before to provide us with a unique file name.
    NSString *imagePath = [NSString stringWithFormat:@"%@/iPhoneImage.png", documentsDirectory];

    // This creates PNG NSData for the UIImageView imageView's image.
    UIImageView *imageView;
    NSData *imageData = UIImagePNGRepresentation(imageView.image);

    // Uncomment the line below to view the image's file path in the Debugger Console. (Command+Shift+R)
    NSLog(@"Image Directory: %@", imagePath);

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

How do I detect that the user selected an image when the imagePicker view controller is presented ?

If they select an image I want to call the saveImage method.

Regards, Stephen


You need to access the UIImagePickerControllerDelegate methods. The link brings you to the one you want. Make sure that you set the picker delegate!

Inside the method you just need to check if the UIImagePickerControllerMediaType key of the info dictionary is set to a kUTTypeImage. Then call your function.


in the

-(void) imagePickerController:(UIImagePickerController *)picker 
        didFinishPickingMediaWithInfo:(NSDictionary *)info  

delegate method of UIImagePickerControllerDelegate.

Edit: reread your question and realized you want to save to your temp path or somewhere, not the phone's photo album.

0

精彩评论

暂无评论...
验证码 换一张
取 消