我正在尝试使用捕获图像AVFoundation
。我正在使用以下代码。
//in interface
AVCaptureDeviceInput *inputBack;
AVCaptureStillImageOutput *outputBack;
AVCaptureConnection *videoConnection;
AVCaptureVideoPreviewLayer *captureVideoPreviewLayer;
-(void)toStartCameraSession
{
if (!session)
{
NSLog(@"View Will Appear Session Called");
session = [[AVCaptureSession alloc] init];
NSArray *devices=[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
inputBack = [AVCaptureDeviceInput deviceInputWithDevice:[devices objectAtIndex:0] error:nil];
[session addInput:inputBack];
//add the output to session
outputBack = [[AVCaptureStillImageOutput alloc]init];
if ([session canAddOutput:outputBack])
{
[session addOutput:outputBack];
}
else
{
NSLog(@"Error on add output, addOutput");
}
session.sessionPreset = AVCaptureSessionPresetPhoto;
// Create the preview layer
captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
CGRect bounds=captureView.layer.bounds;
captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
captureVideoPreviewLayer.bounds=bounds;
captureVideoPreviewLayer.position=CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
[captureVideoPreviewLayer setFrame:CGRectMake(0, 0, self.captureView.frame.size.width, self.captureView.frame.size.height)];
// Set backgrounds colors
[captureVideoPreviewLayer setBackgroundColor:[UIColor clearColor].CGColor];
AVCaptureConnection *previewLayerConnection=captureVideoPreviewLayer.connection;
if ([previewLayerConnection isVideoOrientationSupported])
{
[previewLayerConnection setVideoOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
}
[self.captureView.layer addSublayer:captureVideoPreviewLayer];
}
}
-(void)takePhoto
{
videoConnection = nil;
//Find The Connection With Type
for (AVCaptureConnection *connection in outputBack.connections)
{
NSLog(@"**********takephoto*********");
for (AVCaptureInputPort *port in [connection inputPorts]) {
if ([[port mediaType] isEqual:AVMediaTypeVideo])
{
videoConnection = connection;
break;
}
}
if (videoConnection)
{
break;
}
}
//Capture the image Asynchronous
[outputBack captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:
^(CMSampleBufferRef imageSampleBuffer, NSError *error)
{
NSLog(@"*****fffff*****takephoto*********");
if (imageSampleBuffer != NULL)
{
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
UIImage *imageTaked = [[UIImage alloc] initWithData:imageData];
NSLog(@"captured image in start ---- %@",tempimgview.image);
}
}];
[session stopRunning];
}
我正在调用toStartCameraSession
方法。ViewWillAppear
它有时工作,有时不工作。
任何帮助将不胜感激。谢谢。