Cropping image captured by AVCaptureSession

半世苍凉 提交于 2019-11-29 06:24:32
Prabh

Hope this meets your requirements

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

you can use this api from AVFoundation: AVMakeRectWithAspectRatioInsideRect

it will return the crop region for an image in a bounding region, apple doc is here: https://developer.apple.com/library/ios/Documentation/AVFoundation/Reference/AVFoundation_Functions/Reference/reference.html

I think this is just simple as this

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

with kMargin and kSquareSize (20point and 280point in my case) are the margin and Scanning area respectively

Then perform cropping

CGRect cropRect = [self computeCropRect:cgCapturedImageRef];
CGImageRef croppedImageRef = CGImageCreateWithImageInRect(cgCapturedImageRef, cropRect);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!