如何获得 AVCaptureStillImageOutput 与 AVCaptureVideoPreviewLayer 相同的纵横比?
Posted
技术标签:
【中文标题】如何获得 AVCaptureStillImageOutput 与 AVCaptureVideoPreviewLayer 相同的纵横比?【英文标题】:How to get AVCaptureStillImageOutput same aspect ratio as the AVCaptureVideoPreviewLayer? 【发布时间】:2015-07-29 11:22:58 【问题描述】:我正在使用AVFoundation
拍摄图像。我正在使用AVCaptureVideoPreviewLayer
在屏幕上显示摄像机源。此预览层的框架获取具有动态尺寸的UIView
的边界:
AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
CALayer *rootLayer = [self.cameraFeedView layer];
[rootLayer setMasksToBounds:YES];
CGRect frame = self.cameraFeedView.frame;
[previewLayer setFrame:frame];
previewLayer.frame = rootLayer.bounds;
[rootLayer insertSublayer:previewLayer atIndex:0];
我正在使用AVCaptureStillImageOutput
来捕捉图像:
AVCaptureStillImageOutput *stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
[stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection
completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
if (imageDataSampleBuffer != NULL)
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *capturedImage = [UIImage imageWithData:imageData];
];
我的问题是捕获的图像是 iPhone 摄像头的大小(1280x960 - 前置摄像头),但我需要它与预览层的纵横比相同。例如,如果预览层的大小是 150x100,我需要捕获的图像是 960x640。有什么解决办法吗?
【问题讨论】:
尝试调整图片大小 ***.com/questions/612131/… ***.com/questions/17018617/… 我已经尝试过调整大小,但由于纵横比不同,调整后的图像看起来被压扁了。我可以裁剪图像,但没有办法只从预览层获取原始帧吗? 【参考方案1】:我也进入 counter 同样的问题。您必须裁剪或调整输出静止图像的大小。但是您应该注意到输出仍然是比例和图像方向。
预览图层方框
CGFloat width = CGRectGetWidth(self.view.bounds);
[self.captureVideoPreviewLayer setFrame:CGRectMake(0, 0, width, width)];
[self.cameraView.layer addSublayer:self.captureVideoPreviewLayer];
计算裁剪图像的帧
[self.captureStillImageOutput captureStillImageAsynchronouslyFromConnection:captureConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
NSData *data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [[UIImage alloc] initWithData:data];
CGRect cropRect = CGRectMake((image.size.height - image.size.width) / 2, 0, image.size.width, image.size.width);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation]; // always UIImageOrientationRight
CGImageRelease(imageRef);
];
【讨论】:
以上是关于如何获得 AVCaptureStillImageOutput 与 AVCaptureVideoPreviewLayer 相同的纵横比?的主要内容,如果未能解决你的问题,请参考以下文章