Ios 扭曲的CVImageBuffer到UIImage
我有以下函数将CVImageBugger转换为UIImage。出来的图像总是有点失真。我在UIImageView中显示此函数的返回值,该视图设置为“aspect fill”。有什么好处Ios 扭曲的CVImageBuffer到UIImage,ios,uiimageview,uiimage,cgimage,ciimage,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(o
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
}
CVImageBuffer不包含方向信息,可能这就是最终UIImage失真的原因
CVImageBuffer的默认方向始终是景观,就像iPhone的Home按钮位于右侧一样,无论您是否以纵向方式捕获视频
因此,我们需要为图像添加良好的方向信息:
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()
}
谢谢云。。但不幸的是,它仍然很长。。此外,我的图像没有方向错误。只是拉长了…@7球,你能提供截图吗?