扭曲的CVImageBuffer到UIImage

时间:2018-05-23 01:20:23

标签: ios uiimageview uiimage cgimage ciimage

我有以下功能可将CVImageBugger转换为UIImage。出来的图像总是有点扭曲。我在UIImageView中显示此函数的返回值,该值设置为'aspect fill'。是什么给了?...

private func convert(buffer: CVImageBuffer) -> UIImage? {
    let cmage: CIImage = CIImage(cvPixelBuffer: buffer)
    let context: CIContext = CIContext(options: nil)
    if let cgImage: CGImage = context.createCGImage(cmage, from: cmage.extent) {
        return UIImage(cgImage: cgImage)
    }
    return nil
}

1 个答案:

答案 0 :(得分:0)

CVImageBuffer不包含方向信息,可能是最终UIImage失真的原因。

CVImageBuffer的默认方向始终为横向(就像iPhone的主页按钮位于右侧),无论您是否以纵向方式捕捉视频。

因此我们需要为图像添加良好的方向信息:

extension CIImage {
    func orientationCorrectedImage() -> UIImage? {
        var imageOrientation = UIImageOrientation.up
        switch UIApplication.shared.statusBarOrientation {
        case UIInterfaceOrientation.portrait:
            imageOrientation = UIImageOrientation.right
        case UIInterfaceOrientation.landscapeLeft:
            imageOrientation = UIImageOrientation.down
        case UIInterfaceOrientation.landscapeRight:
            imageOrientation = UIImageOrientation.up
        case UIInterfaceOrientation.portraitUpsideDown:
            imageOrientation = UIImageOrientation.left
        default:
            break;
        }

        var w = self.extent.size.width
        var h = self.extent.size.height

        if imageOrientation == .left || imageOrientation == .right || imageOrientation == .leftMirrored || imageOrientation == .rightMirrored {
            swap(&w, &h)
        }

        UIGraphicsBeginImageContext(CGSize(width: w, height: h));
        UIImage.init(ciImage: self, scale: 1.0, orientation: imageOrientation).draw(in: CGRect(x: 0, y: 0, width: w, height: h))
        let uiImage:UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();

        return uiImage
    }
}

然后将其与您的代码一起使用:

private func convert(buffer: CVImageBuffer) -> UIImage? {
    let ciImage: CIImage = CIImage(cvPixelBuffer: buffer)
    return ciImage.orientationCorrectedImage()
}