AVFoundation裁剪根据预览宽高比捕获静止图像 [英] AVFoundation crop captured still image according to the preview aspect ratio

查看:81
本文介绍了AVFoundation裁剪根据预览宽高比捕获静止图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题大致与此类似:

My question is mostly similar to this one:

裁剪AVCaptureSession捕获的图像

我有一个使用AVFoundation拍摄静止图像的应用程序。我的AVCaptureVideoPreviewLayer具有AVLayerVideoGravityResizeAspectFill视频重力,从而使得向用户显示的预览图片从顶部和底部部分被裁剪。

I have an application 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?

提前致谢。

推荐答案

我使用了 UIImage + Resize 类别类别rel =nofollow>这里我写了一些新方法来完成这项工作。我重新格式化了一些代码,看起来更好,没有经过测试,但它应该可行。 :))

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

这篇关于AVFoundation裁剪根据预览宽高比捕获静止图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆