有没有办法在不通过Apple控件的情况下在iPhone上的代码中拍照?我见过很多应用程序,但我不确定要使用哪种API调用。
答案 0 :(得分:37)
编辑:正如下面的评论所示,我现在已经明确地展示了如何声明和初始化AVCaptureSession。似乎有少数人正在初始化错误或将AVCaptureSession声明为方法中的局部变量。这不行。
以下代码允许在没有用户输入的情况下使用AVCaptureSession拍照:
// Get all cameras in the application and find the frontal camera.
AVCaptureDevice *frontalCamera;
NSArray *allCameras = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
// Find the frontal camera.
for ( int i = 0; i < allCameras.count; i++ ) {
AVCaptureDevice *camera = [allCameras objectAtIndex:i];
if ( camera.position == AVCaptureDevicePositionFront ) {
frontalCamera = camera;
}
}
// If we did not find the camera then do not take picture.
if ( frontalCamera != nil ) {
// Start the process of getting a picture.
session = [[AVCaptureSession alloc] init];
// Setup instance of input with frontal camera and add to session.
NSError *error;
AVCaptureDeviceInput *input =
[AVCaptureDeviceInput deviceInputWithDevice:frontalCamera 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];
}
}];
}
}
}
}
会话变量的类型为AVCaptureSession,并已在类的.h文件中声明(作为属性或类的私有成员):
AVCaptureSession *session;
然后需要在某个地方对其进行初始化,例如在班级&#39; init方法:
session = [[AVCaptureSession alloc] init]
答案 1 :(得分:25)
是的,有两种方法可以做到这一点。一个在iOS 3.0+中可用的是使用UIImagePickerController
类,将showsCameraControls
属性设置为NO,并将cameraOverlayView
属性设置为您自己的自定义控件。 iOS 4.0+中提供的两项功能是配置AVCaptureSession
,使用相应的相机设备为AVCaptureDeviceInput
提供AVCaptureStillImageOutput
。第一种方法更简单,适用于更多iOS版本,但第二种方法可以更好地控制照片分辨率和文件选项。