[英]How to save/capture photo in portrait mode in IOS AVFoundation? Xcode 10.2 Swift 5
I set photoOutput.connection orientation to portrait but image continues to save in landscape mode.我将 photoOutput.connection 方向设置为纵向,但图像继续以横向模式保存。 Am I supposed to change the settings somewhere else?
我应该在其他地方更改设置吗?
func configurePhotoOutput() throws {
guard let captureSession = self.captureSession else { throw CameraControllerError.captureSessionIsMissing }
self.photoOutput = AVCapturePhotoOutput()
self.photoOutput?.connection(with: .video)?.videoOrientation = .portrait
self.photoOutput?.isHighResolutionCaptureEnabled = true
self.photoOutput!.setPreparedPhotoSettingsArray([AVCapturePhotoSettings(format: [AVVideoCodecKey : AVVideoCodecJPEG])], completionHandler: nil)
if captureSession.canAddOutput(self.photoOutput!) { captureSession.addOutput(self.photoOutput!) }
captureSession.startRunning()
}
When photo is being captured, inside delegate method of AVCapturePhotoCaptureDelegate where you get the image at that time you have to provide orientation for the image.捕获照片时,在获取图像的 AVCapturePhotoCaptureDelegate 的委托方法中,您必须为图像提供方向。
var cameraPosition: AVCaptureDevice.Position = .front
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let image = photo.cgImageRepresentation()?.takeUnretainedValue() {
let finalImage = UIImage(cgImage: image, scale: 1, orientation: UIDevice.current.orientation.getUIImageOrientationFromDevice(for: cameraPosition))
print(finalImage)
}
}
extension UIDeviceOrientation {
func getUIImageOrientationFromDevice(for position: AVCaptureDevice.Position) -> UIImage.Orientation {
if position == .front {
switch self {
case .portrait, .faceUp: return UIImage.Orientation.leftMirrored
case .portraitUpsideDown, .faceDown: return UIImage.Orientation.left
case .landscapeLeft, .unknown: return UIImage.Orientation.down // this is the base orientation
case .landscapeRight: return UIImage.Orientation.up
}
} else {
switch self {
case .faceUp, .landscapeLeft, .unknown: return UIImage.Orientation.up
case .portraitUpsideDown: return UIImage.Orientation.left
case .portrait, .faceDown: return UIImage.Orientation.right
case .landscapeRight: return UIImage.Orientation.down
}
}
}
}
It's working for me.它对我有用。 Please let me know if you're having any issue in the above code.
如果您在上述代码中遇到任何问题,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.