Swift UI 相机显示纵向视图但图像变成横向

Swift UI camera shows portrait view but image turns out landscape

我正在尝试让相机预览和照片在 swiftUI 应用程序中工作,我可以显示预览并拍摄照片,但比例出现错误。预览画面看起来不错,但是一旦捕捉发生,它就会变形并且不能保持纵向。

预览屏幕如下所示:

一些代码:

class CameraController: UIViewController {
    //...
    override func viewDidLoad() {
        //...
        // Setup preview layer
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        previewLayer?.videoGravity = .resizeAspectFill
        previewLayer?.connection?.videoOrientation = .portrait
        previewLayer?.frame = view.frame
        view.layer.insertSublayer(previewLayer!, at: 0)
        //...
    }
}

但是在我拍完照片后,我在 VStack 中显示的 Image 看起来像:

密码是:

VStack {
    Image(uiImage: self.inputImage!)
        .resizable()
        .aspectRatio(contentMode: .fit)
        .edgesIgnoringSafeArea(.all)
}

我使用 .fit 是因为我想看到整个事情,但结果完全错了。此外,这是我在 viewDidLoad:

中发生的相机设置代码
captureSession.beginConfiguration()

// Get device
captureDevice = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .back)

do {
    // Create input
    let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice!)
    captureSession.addInput(captureDeviceInput)

    // Create output
    photoOutput = AVCapturePhotoOutput()
    captureSession.sessionPreset = .photo
    photoOutput?.setPreparedPhotoSettingsArray(
        [AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg])],
        completionHandler: nil
    )
    captureSession.connections.first?.videoOrientation = .portrait // tested with and and without this line
    captureSession.addOutput(photoOutput!)
    captureSession.commitConfiguration()
} catch {
    print(error)
}

非常感谢任何帮助!

它 returns 仅在横向上,因为用 in-app 相机拍摄的图像有一个方向。您需要对其进行归一化并显示它。

我用

扩展了 UIImage
func fixOrientation(img:UIImage) -> UIImage {

  if (img.imageOrientation == UIImageOrientation.Up) { 
      return img;
  }

  UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale);
  let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
  img.drawInRect(rect)

  let normalizedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext();
  return normalizedImage;

}

这里的原始答案: Normalize Pictures taken by camera

此外,我刚刚对 ImagePickerManager 的复制和粘贴解决方案做了一些更改:

ImagePickerManager