2010-09-02 40 views
1

我试图将选定的图像保存到目录。我的代码如下:UIImagePickerController - 保存选定的图像

-(IBAction)attachPhotosButton 
{ 
    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]; 
} 

如何检测到用户在显示imagePicker视图控制器时选择了图像?

如果他们选择一个图像我想调用saveImage方法。

问候, 斯蒂芬

回答

2

您需要访问UIImagePickerControllerDelegate方法。链接将您带到您想要的那个。确保你设置了选择器代表!

在方法内部,您只需检查info字典的UIImagePickerControllerMediaType键是否设置为kUTTypeImage。然后调用你的函数。

1

在UIImagePickerControllerDelegate的

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

委托方法。

编辑:重读您的问题,并意识到您想保存到您的临时路径或某处,而不是手机的相册。

+0

如何从savedPhotosAlbum中获取图像?你需要再次呈现UIImagePickerController吗? – vodkhang 2010-09-02 16:09:31

+0

请阅读UIImagePickerControllerDelegate @MishieMoo上的文档,以便在另一个答案中提供。 – 2010-09-02 16:14:46

相关问题