【问题标题】:AVFoundation crop captured still image according to the preview aspect ratioAVFoundation 根据预览纵横比裁剪捕获的静止图像
【发布时间】:2011-08-11 15:03:27
【问题描述】:

我的问题与这个问题大体相似:

Cropping image captured by AVCaptureSession

我有一个使用 AVFoundation 来捕捉静止图像的应用程序。我的 AVCaptureVideoPreviewLayer 具有 AVLayerVideoGravityResizeAspectFill 视频重力,因此可以从顶部和底部裁剪向用户显示的预览图片。

当用户按下“捕获”按钮时,实际捕获的图像与显示给用户的预览图片不同。我的问题是如何相应地裁剪捕获的图像?

提前致谢。

【问题讨论】:

  • 捕获的图像与预览图像不同,因为您正在调整宽高比填充的大小,对吗?那么,为什么不将属性更改为 AVLayerVideoGravityResizeAspect 或调整预览层的尺寸以匹配捕获图像的比例?
  • 您找到解决问题的方法了吗?

标签: objective-c ios ios4 avfoundation


【解决方案1】:

我使用here 中提供的UIImage+Resize 类别和我编写的一些新方法来完成这项工作。我重新格式化了一些代码以使其看起来更好并且未经测试,但它应该可以工作。 :))

- (UIImage*)cropAndResizeAspectFillWithSize:(CGSize)targetSize
                       interpolationQuality:(CGInterpolationQuality)quality {

    UIImage *outputImage = nil;
    UIImage *imageForProcessing = self;

    // crop center square (AspectFill)
    if (self.size.width != self.size.height) {
        CGFloat shorterLength = 0;
        CGPoint origin = CGPointZero;
        if (self.size.width > self.size.height) {
            origin.x = (self.size.width - self.size.height)/2;
            shorterLength = self.size.height;
        }
        else {
            origin.y = (self.size.height - self.size.width)/2;
            shorterLength = self.size.width;
        }
        imageForProcessing = [imageForProcessing normalizedImage];
        imageForProcessing = [imageForProcessing croppedImage:CGRectMake(origin.x, origin.y, shorterLength, shorterLength)];
    }
    outputImage = [imageForProcessing resizedImage:targetSize interpolationQuality:quality];
    return outputImage;
}

// fix image orientation, which may wrongly rotate the output.
- (UIImage *)normalizedImage {
    if (self.imageOrientation == UIImageOrientationUp) return self;

    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    [self drawInRect:(CGRect){0, 0, self.size}];
    UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return normalizedImage;
}

【讨论】:

  • 这种方法如何帮助裁剪图像?
  • 看起来它调整了给定图像的大小,但没有裁剪它
  • 你是对的。我也意识到了这一点,但忘了修正我的答案。很快就会这样做;)
  • 你去看看吧
  • 谢谢,我会试试的。如果我还需要考虑图像的 x 和 y,它会起作用吗?就我而言,我将 AVCamera 的 VideoPreviewLayer 定位在屏幕的 x=3, y=67 位置,尺寸为 310X310
猜你喜欢
  • 2011-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-31
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多