在没有显示控件的情况下在iPhone上拍照

有没有办法在没有通过苹果控件的iPhone上的代码拍照? 我已经看到了一堆应用程序这样做,但我不知道什么API调用使用。

是的,有两种方法可以做到这一点。 一个在iOS 3.0+中可用的是使用UIImagePickerController类,将showsCameraControls属性设置为NO,并将cameraOverlayView属性设置为您自己的自定义控件。 两种iOS 4.0+可用,configuration一个AVCaptureSession ,使用适当的相机设备提供一个AVCaptureDeviceInputAVCaptureStillImageOutput 。 第一种方法要简单得多,适用于更多的iOS版本,但第二种方法可以更好地控制照片分辨率和文件选项。

编辑:正如在下面的评论中所build议的,我现在已经明确地显示了AVCaptureSession如何声明和初始化。 似乎有一些做初始化错误或声明AVCaptureSession作为一个方法中的局部variables。 这是行不通的。

以下代码允许在没有用户input的情况下使用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]; } }]; } } } } 

sessionvariables的types是AVCaptureSession,并且已经在类的.h文件中声明(作为一个属性或者作为类的私有成员):

 AVCaptureSession *session; 

然后需要在类的init方法中初始化某个地方:

 session = [[AVCaptureSession alloc] init]