我需要iOS相机在没有用户输入的情况下拍照。我该怎么做呢?到目前为止,这是我的代码:
-(void)initCapture{
AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] init];
AVCaptureStillImageOutput *newStillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:
AVVideoCodecJPEG, AVVideoCodecKey,
nil];
[newStillImageOutput setOutputSettings:outputSettings];
AVCaptureSession *newCaptureSession = [[AVCaptureSession alloc] init];
if ([newCaptureSession canAddInput:newVideoInput]) {
[newCaptureSession addInput:newVideoInput];
}
if ([newCaptureSession canAddOutput:newStillImageOutput]) {
[newCaptureSession addOutput:newStillImageOutput];
}
self.stillImageOutput = newStillImageOutput;
}
我还需要添加什么,以及从哪里开始?我不想拍摄视频,只拍摄一张静止图片。另外,之后如何将图像转换为UIImage?感谢
答案 0 :(得分:1)
了解如何在没有用户输入的情况下拍摄照片的AVCaptureSession。您需要将AVCaptureDevice添加到会话中。
答案 1 :(得分:1)
您已获得AVCaptureStillImageOutput,stillImageOutput
。此外,您需要将捕获会话存储在以后可以获取的位置。称之为self.sess
。然后:
AVCaptureConnection *vc =
[self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
[self.sess startRunning];
[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:vc
completionHandler:
^(CMSampleBufferRef buf, NSError *err) {
NSData* data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:buf];
UIImage* im = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
UIImageView* iv = [[UIImageView alloc] initWithFrame:someframe];
iv.contentMode = UIViewContentModeScaleAspectFit;
iv.image = im;
[self.view addSubview: iv];
[self.iv removeFromSuperview]; // in case we already did this
self.iv = iv;
[self.sess stopRunning];
});
}];
答案 2 :(得分:0)
正如@Salil所说,苹果的官方AVFoundation非常有用,看看它就能理解主要概念。然后,您可以下载示例代码以了解如何实现目标。
Here is the sample code使用预览图片拍摄静止图像。