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()
}