将 CVImageBuffer 扭曲到 UIImage
Posted
技术标签:
【中文标题】将 CVImageBuffer 扭曲到 UIImage【英文标题】:Distorted CVImageBuffer to UIImage 【发布时间】:2018-05-23 01:20:22 【问题描述】:我有以下将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】: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()
【讨论】:
谢谢Yun.. 但不幸的是它仍然很长.. 另外我的图像方向没有正确。它只是拉长了.. @7ball,你能提供截图吗?以上是关于将 CVImageBuffer 扭曲到 UIImage的主要内容,如果未能解决你的问题,请参考以下文章