开发者

AVFoundation crop captured still image according to the preview aspect ratio

My question is mostly similar to this one:

Cropping image captured by AVCaptureSession

I have an applicati开发者_C百科on which uses AVFoundation for capturing still images. My AVCaptureVideoPreviewLayer has AVLayerVideoGravityResizeAspectFill video gravity thus making preview picture which is shown to the user to be cropped from the top and from the bottom parts.

When user is pressing "Capture" button, the image actually captured is differs from the preview picture shown to user. My question is how to crop captured image accordingly?

Thanks in advance.


I used UIImage+Resize category provided in here with some new methods I wrote to do the job. I reformatted some code to look better and not tested, but it should work. :))

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜