2011-04-25 68 views
10

我正在写一个iPhone应用程序,它使用AVFoundation拍摄照片并对其进行裁剪。 该应用类似于QR码阅读器:它使用带覆盖的AVCaptureVideoPreviewLayer。 覆盖有一个正方形。我想裁剪图像,以便裁剪后的图像与用户在广场内的位置完全相同。由AVCaptureSession捕获的裁剪图像

预览图层具有重力AVLayerVideoGravityResizeAspectFill。

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

是否有人知道我如何获得此信息,或者如果有不同的方法来裁剪图像。 (p.s.捕获预览的屏幕截图不是一个选项,据我所知可能导致应用程序被拒绝)。

预先感谢您

回答

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; 
} 
+0

它不会帮助因为相机也会旋转图像。在这里看到类似的问题http://cmgresearch.blogspot.co.il/2012/07/cropping-results-from.html – Dejell 2013-01-21 18:39:57

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

与kMargin和kSquareSize(20point和280point在我的情况只是简单的)分别为边距和扫描区域

然后执行cro pping

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