我只需要从相机中获取一张照片并将其保存到文件中.解决方法 我用这段代码用前置摄像头拍照.并非所有代码都是我的,但我没有找到原始来源的链接.此代码还会产生快门声.图像质量不是很好(它很暗)所以代码需要一两个调整.
-(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);
也产生了良好的结果 – 因此不需要一整秒的滞后.
请注意,此代码用于拍摄带有正面相机的照片 – 如果您需要使用背面照相机,我相信您会知道如何修补它.
总结以上是内存溢出为你收集整理的ios – Objective-C在没有相机界面的情况下拍摄照片的简单方法.只需从相机获取图片并保存到文件全部内容,希望文章能够帮你解决ios – Objective-C在没有相机界面的情况下拍摄照片的简单方法.只需从相机获取图片并保存到文件所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)