-1

如何将图像从 UIImagePickerController 显示到另一个 ViewController.xib?

我有“ViewController1”,在这里我得到了这个代码:

- (IBAction)goCamera:(id)sender {


    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    [picker setSourceType:UIImagePickerControllerSourceTypeCamera];
    [self presentModalViewController:picker animated:YES];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissModalViewControllerAnimated:YES];
    UIImageView *theimageView = [[UIImageView alloc]init];
    theimageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

}

我怎样才能去“ViewController2”并在那里显示拍摄的照片?我使用 ViewController1 拍摄照片,我想在 ViewController2 中显示这张拍摄的照片,其中我有一个 UIImageView。非常感谢

4

1 回答 1

2

最好的方法是在您收到图像后立即将图像保存在应用程序的文件夹中。

这很重要,因为它有助于内存管理

您可以放开图像数据,而不是在应用程序中传递它。

我使用类似于以下的代码:

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

    UIImage *originalImage, *editedImage, *imageToSave;
    editedImage = (UIImage *) [info objectForKey:
                               UIImagePickerControllerEditedImage];
    originalImage = (UIImage *) [info objectForKey:
                                 UIImagePickerControllerOriginalImage];
    imageToSave = (editedImage!=nil ? editedImage : originalImage);


    // Check if the image was captured from the camera
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        // Save the image to the camera roll
        UIImageWriteToSavedPhotosAlbum(imageToSave, nil, nil, nil);
    }

    NSString *docspath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filepathJPG = [docspath stringByAppendingPathComponent:@"imagefile.jpg"];

    NSData *data = UIImageJPEGRepresentation(imageToSave, 0.8);
    BOOL result = [data writeToFile:filepathJPG atomically:YES];
    NSLog(@"Saved to %@? %@", filepathJPG, (result? @"YES": @"NO") );

    [picker dismissModalViewControllerAnimated:YES];
}

然后在您的其他视图控制器中,无论您希望加载图像(viewDidLoad、viewWillAppear 还是其他任何地方),都放:

NSString *docspath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filepathJPG = [docspath stringByAppendingPathComponent:@"imagefile.jpg"];

UIImage *img = [UIImage imageWithContentsOfFile: filepathJPG];
if (img != nil) {
    // assign the image to the imageview, 
    myImageView.image = img;

    // Optionally adjust the size
    BOOL adjustToSmallSize = YES;
    CGRect smallSize = (CGRect){0,0,100,100};
    if (adjustToSmallSize) {
        myImageView.bounds = smallSize;
    }

}
else {
    NSLog(@"Image hasn't been created");
}

希望有帮助

于 2012-12-12T20:56:27.693 回答