我使用AVCaptureVideoPreviewLayer以编程方式启动摄像头,然后使用以下代码自动拍照。图片的输出分辨率不是很高,比我们通常使用原生相机拍照还要亮。这有什么问题,有人可以帮忙吗?
-(void) capturePicture
{
// Get all cameras in the application and find the frontal camera.
AVCaptureDevice *backCamera;
NSArray *allCameras = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
// Find the back camera.
for ( int i = 0; i < allCameras.count; i++ ) {
AVCaptureDevice *camera = [allCameras objectAtIndex:i];
if ( camera.position == AVCaptureDevicePositionBack ) {
backCamera = camera;
}
}
// If we did not find the camera then do not take picture.
if ( backCamera != nil ) {
// Start the process of getting a picture.
AVCaptureSession *session = [[AVCaptureSession alloc] init];
// Setup instance of input with back camera and add to session.
NSError *error;
AVCaptureDeviceInput *input =
[AVCaptureDeviceInput deviceInputWithDevice:backCamera error:&error];
if ( !error && [session canAddInput:input] ) {
// Add frontal camera to this session.
[session addInput:input];
// We need to capture still image.
AVCaptureStillImageOutput *output = [[AVCaptureStillImageOutput alloc] init];
// Captured image. settings.
[output setOutputSettings:
[[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil]];
if ( [session canAddOutput:output] )
{
[session addOutput:output];
AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in output.connections) {
for (AVCaptureInputPort *port in [connection inputPorts]) {
if ( [[port mediaType] isEqual:AVMediaTypeVideo] )
{
videoConnection = connection;
break;
}
}
if (videoConnection)
{
break;
}
}
// Finally take the picture
if ( videoConnection )
{
[session startRunning];
[output captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
{
if (imageDataSampleBuffer != NULL)
{
NSData *imageData = [AVCaptureStillImageOutput
jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *photo = [[UIImage alloc] initWithData:imageData];
UIImageWriteToSavedPhotosAlbum(photo, nil, nil, nil);
[session stopRunning];
NSInvocation *myInvocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(endScreen)]];
[myInvocation setSelector:@selector(endScreen)];
[myInvocation setTarget:self];
appDelegate.bImageTaken = YES;
UIImageWriteToSavedPhotosAlbum(photo, nil, nil, nil);
[NSTimer scheduledTimerWithTimeInterval:0.5 invocation:myInvocation repeats:NO];
}
}];
}
}
}
}
}