gpt4 book ai didi

ios - 如何获得与 AVCaptureVideoPreviewLayer 相同的纵横比的 AVCaptureStillImageOutput?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:14:22 25 4
gpt4 key购买 nike

我正在使用 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。有解决办法吗?

最佳答案

我也进入柜台同样的问题。您必须裁剪或调整输出静止图像的大小。但是您应该注意到输出仍然是比例和图像方向。

预览图层方框

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);
}];

关于ios - 如何获得与 AVCaptureVideoPreviewLayer 相同的纵横比的 AVCaptureStillImageOutput?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31699078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com