Iphone 裁剪AVCaptureSession捕获的图像
我正在编写一个iPhone应用程序,它使用AVFoundation拍摄照片并进行裁剪。 该应用程序类似于二维码阅读器:它使用带有覆盖层的AVCaptureVideoPreviewLayer。 覆盖层有一个正方形。我想裁剪图像,这样裁剪后的图像就是用户在正方形中放置的位置 预览层具有重力AVLayerVideoGravityResizeAspectFill 看起来相机实际捕获的内容与用户在预览层中看到的不完全相同。这意味着我需要从预览坐标系移动到捕获图像坐标系,以便裁剪图像。为此,我认为我需要以下参数: 1.视图大小和捕获图像大小之间的比率。 2.指示捕获图像的哪个部分与预览层中显示的内容相匹配的信息 是否有人知道我如何获得这些信息,或者是否有其他方法来裁剪图像 (请注意,捕获预览屏幕截图不是一个选项,因为我知道这可能会导致应用被拒绝)Iphone 裁剪AVCaptureSession捕获的图像,iphone,avfoundation,Iphone,Avfoundation,我正在编写一个iPhone应用程序,它使用AVFoundation拍摄照片并进行裁剪。 该应用程序类似于二维码阅读器:它使用带有覆盖层的AVCaptureVideoPreviewLayer。 覆盖层有一个正方形。我想裁剪图像,这样裁剪后的图像就是用户在正方形中放置的位置 预览层具有重力AVLayerVideoGravityResizeAspectFill 看起来相机实际捕获的内容与用户在预览层中看到的不完全相同。这意味着我需要从预览坐标系移动到捕获图像坐标系,以便裁剪图像。为此,我认为我需要以下
提前感谢您希望这符合您的要求
- (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;
}
我觉得就这么简单
- (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(我的例子中是20点和280点)分别是边距和扫描区域
然后进行裁剪
CGRect cropRect = [self computeCropRect:cgCapturedImageRef];
CGImageRef croppedImageRef = CGImageCreateWithImageInRect(cgCapturedImageRef, cropRect);
您可以从AVFoundation:AVMakeRectWithAspectRatioInsideRect使用此api 它将返回边界区域中图像的裁剪区域,apple doc位于此处:
这不会有帮助,因为相机也会旋转图像。这里有一个类似的问题