使用AVFoundation捕获图像预览,就像在屏幕上一样

时间:2013-04-23 11:57:55

标签: ios objective-c avfoundation

我设置了AVCaptureSession预设的PhotoPreset

self.session.sessionPreset = AVCaptureSessionPresetPhoto;

然后使用

在我的视图中添加一个新图层
 AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
CALayer *rootLayer = [self.view layer];
[rootLayer setMasksToBounds:YES];
[previewLayer setFrame:[rootLayer bounds]];
[rootLayer addSublayer:previewLayer];

到目前为止一切顺利,但是当我想拍摄图像时,我会使用下面的代码

 AVCaptureConnection *videoConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];

[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
 {

     [self.session stopRunning];

     NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
     UIImage *image = [[UIImage alloc] initWithData:imageData ];

     self.imageView.image = image; //IMAGEVIEW IS WITH THE BOUNDS OF SELF.VIEW
     image = nil;


 }];

捕获图像很好,但是与屏幕上显示的AVCaptureVideoPreviewLayer相比,捕获的图像不同。我真正想要做的是将捕获显示为出现在AVCapturePreviewLayer图层上。我怎样才能做到这一点?我应该如何根据self.view的边界调整和捕获捕获的图像?

1 个答案:

答案 0 :(得分:-1)

我不确定这会对您有所帮助,但是当您谈到裁剪图像时,我在ImagePickerView中使用以下代码裁剪图像我不确定这会对您有所帮助

- (void)imagePickerController:(UIImagePickerController *)picker 
didFinishPickingMediaWithInfo:(NSDictionary *)info {
    self.lastChosenMediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([lastChosenMediaType isEqual:(NSString *)kUTTypeImage]) {
        UIImage *chosenImage = [info objectForKey:UIImagePickerControllerEditedImage];
        UIImage *shrunkenImage = shrinkImage(chosenImage, imageFrame.size);
        self.imagee = shrunkenImage;
        selectImage.image = imagee;

    }     [picker dismissModalViewControllerAnimated:YES];
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {    
    [picker dismissModalViewControllerAnimated:YES];
}

// function for cropping images you can do some changes in parameter as per your requirements  
static UIImage *shrinkImage(UIImage *original, CGSize size) {
    CGFloat scale = [UIScreen mainScreen].scale;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGContextRef context = CGBitmapContextCreate(NULL, size.width * scale,
                                                 size.height * scale, 8, 0, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGContextDrawImage(context,
                       CGRectMake(0, 0, size.width * scale, size.height * scale),
                       original.CGImage);
    CGImageRef shrunken = CGBitmapContextCreateImage(context);
    UIImage *final = [UIImage imageWithCGImage:shrunken];

    CGContextRelease(context);
    CGImageRelease(shrunken);   

    return final;
}