簡體   English   中英

如何讓AVCaptureStillImageOutput與AVCaptureVideoPreviewLayer具有相同的寬高比?

[英]How to get AVCaptureStillImageOutput same aspect ratio as the AVCaptureVideoPreviewLayer?

我正在使用AVFoundation捕獲圖像。 我正在使用AVCaptureVideoPreviewLayer在屏幕上顯示相機Feed。 此預覽圖層的框架獲取具有動態尺寸的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);
}];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM