Objective-C无需相机界面即可拍摄照片的简单方法。 只需从相机获取图片并保存到文件

我无法find一个没有相机界面拍照的简单方法。 我只需要从相机中获取图片并将其保存到文件。

我用这个代码与正面相机拍照。 不是所有的代码都是我的,但是我没有find原始源代码的链接。 此代码也会产生快门声。 图像质量不是很好(这是相当黑暗的),所以代码需要调整或两个。

-(void) takePhoto { AVCaptureDevice *frontalCamera; NSArray *allCameras = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; for ( int i = 0; i < allCameras.count; i++ ) { AVCaptureDevice *camera = [allCameras objectAtIndex:i]; if ( camera.position == AVCaptureDevicePositionFront ) { frontalCamera = camera; } } if ( frontalCamera != nil ) { photoSession = [[AVCaptureSession alloc] init]; NSError *error; AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:frontalCamera error:&error]; if ( !error && [photoSession canAddInput:input] ) { [photoSession addInput:input]; AVCaptureStillImageOutput *output = [[AVCaptureStillImageOutput alloc] init]; [output setOutputSettings: [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil]]; if ( [photoSession canAddOutput:output] ) { [photoSession 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; } } if ( videoConnection ) { [photoSession startRunning]; [output captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) { if (imageDataSampleBuffer != NULL) { NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer]; UIImage *photo = [[UIImage alloc] initWithData:imageData]; [self processImage:photo]; //this is a custom method } }]; } } } } } 

photoSession是持有takePhoto方法的类的AVCaptureSession * ivar。

编辑(调整):如果您更改if ( videoConnection )块到下面的代码,您将添加1秒的延迟,并获得一个良好的形象。

 if ( videoConnection ) { [photoSession startRunning]; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [output captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRefimageDataSampleBuffer, NSError *error) { if (imageDataSampleBuffer != NULL) { NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer]; UIImage *photo = [[UIImage alloc] initWithData:imageData]; [self processImage:photo]; } }]; }); } 

如果您的应用程序的延迟不可接受,则可以将代码拆分为两部分,并在viewDidAppear (或类似的地方)启动photoSession ,并在需要时立即获取快照 – 通常在某些用户交互之后。

 dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.25 * NSEC_PER_SEC); 

也产生了很好的结果 – 所以不需要整整一秒的时间。

请注意,这段代码是用正面相机写的 – 我相信如果你需要使用背部相机,你将会知道如何修补它。