裁剪AVCaptureSession捕获的图像

时间:2011-04-25 16:37:18

标签: iphone avfoundation

我正在编写一个iPhone应用程序,它使用AVFoundation拍摄照片并裁剪它。 该应用程序类似于QR代码阅读器:它使用带覆盖的AVCaptureVideoPreviewLayer。 叠加层有一个正方形。我想剪裁图像,以便裁剪的图像正好是用户在广场内的位置。

预览图层有重力AVLayerVideoGravityResizeAspectFill。

看起来相机实际拍摄的内容并不完全是用户在预览图层中看到的内容。这意味着我需要从预览坐标系移动到捕获的图像坐标系,以便我可以裁剪图像。为此,我认为我需要以下参数: 1.视图大小与捕获图像大小之间的比例。 2.告知捕获图像的哪一部分与预览图层中显示的内容相匹配的信息。

是否有人知道如何获取此信息,或者是否有其他方法来裁剪图像。

(p.s。捕获预览的屏幕截图不是一个选项,因为我知道它可能会导致应用程序被拒绝。)

提前谢谢

3 个答案:

答案 0 :(得分:5)

希望这符合您的要求

- (UIImage *)cropImage:(UIImage *)image to:(CGRect)cropRect andScaleTo:(CGSize)size {
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGImageRef subImage = CGImageCreateWithImageInRect([image CGImage], cropRect);
    NSLog(@"---------");     
    NSLog(@"*cropRect.origin.y=%f",cropRect.origin.y);
    NSLog(@"*cropRect.origin.x=%f",cropRect.origin.x);

    NSLog(@"*cropRect.size.width=%f",cropRect.size.width);     
    NSLog(@"*cropRect.size.height=%f",cropRect.size.height);     

    NSLog(@"---------");     

    NSLog(@"*size.width=%f",size.width);     
    NSLog(@"*size.height=%f",size.height);     

    CGRect myRect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    CGContextScaleCTM(context, 1.0f, -1.0f);
    CGContextTranslateCTM(context, 0.0f, -size.height);
    CGContextDrawImage(context, myRect, subImage);
    UIImage* croppedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRelease(subImage);     

    return croppedImage;
}

答案 1 :(得分:2)

你可以使用AVFoundation的这个api:AVMakeRectWithAspectRatioInsideRect

它将返回边界区域中图像的裁剪区域,apple doc在这里: https://developer.apple.com/library/ios/Documentation/AVFoundation/Reference/AVFoundation_Functions/Reference/reference.html

答案 2 :(得分:1)

我认为这很简单,因为这个

- (CGRect)computeCropRect:(CGImageRef)cgImageRef
{
    static CGFloat cgWidth = 0;
    static CGFloat cgHeight = 0;

    static CGFloat viewWidth = 320;

    if(cgWidth == 0)
        cgWidth = CGImageGetWidth(cgImageRef);

    if(cgHeight == 0)
        cgHeight = CGImageGetHeight(cgImageRef);

    CGRect cropRect;

    // Only based on width
    cropRect.origin.x = cropRect.origin.y = kMargin * cgWidth / viewWidth;
    cropRect.size.width = cropRect.size.height = kSquareSize * cgWidth / viewWidth;

    return cropRect;
}

使用kMa​​rgin和kSquareSize(在我的情况下为20point和280point)分别是边距和扫描区域

然后执行裁剪

CGRect cropRect = [self computeCropRect:cgCapturedImageRef];
CGImageRef croppedImageRef = CGImageCreateWithImageInRect(cgCapturedImageRef, cropRect);
相关问题