我正在尝试使用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
方法。它有时会工作,有时也不会。
任何帮助都会得到感谢。谢谢。