Swift - AVFoundation 捕获图像方向

Mar*_*rco 3 avfoundation ios landscape-portrait swift

我有一个自定义相机,可以在人像模式下拍照。

我的问题是,如果我尝试以横向方式拍摄照片并保存,那么图片仍会以纵向模式保存。

我有这个功能来设置预览层:

 static func setupPreviewLayer(view: UIView) {
    cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
    switch UIDevice.current.orientation {
    case .portrait:
        cameraPreviewLayer?.connection?.videoOrientation = 
       AVCaptureVideoOrientation.portrait
    case .portraitUpsideDown:
        cameraPreviewLayer?.connection?.videoOrientation = 
          AVCaptureVideoOrientation.portraitUpsideDown
    case .landscapeLeft:
        cameraPreviewLayer?.connection?.videoOrientation =
        AVCaptureVideoOrientation.landscapeLeft
    case .landscapeRight:
        cameraPreviewLayer?.connection?.videoOrientation = 
         AVCaptureVideoOrientation.landscapeRight
    default:
        cameraPreviewLayer?.connection?.videoOrientation = 
         AVCaptureVideoOrientation.portrait
    }
    cameraPreviewLayer?.frame = view.frame
    view.layer.insertSublayer(cameraPreviewLayer!, at: 0)
}
Run Code Online (Sandbox Code Playgroud)

我称之为 viewWillAppear (我认为这不是正确的做法)。

然后我拍了张照片:

@IBAction func takePhotoBtnPressed(_ sender: Any) {
    let settings = AVCapturePhotoSettings()
    useFlash(settings: settings)
    settings.isAutoStillImageStabilizationEnabled = true
    CustomCamera.photoOutput?.capturePhoto(with: settings, delegate: self)
}
Run Code Online (Sandbox Code Playgroud)

并使用此扩展名:

extension FishCameraVC: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
    if let imageData = photo.fileDataRepresentation() {
        image = UIImage(data: imageData)


          performSegue(withIdentifier: "ShowTakenPhoto", sender: nil)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

只要我拍摄人像模式照片,一切都正常,但是当我旋转手机拍摄风景照片时,照片仍然以人像模式拍摄。

这是我第一次使用定制相机,我真的不知道从哪里开始解决这个问题......如果有人能提供帮助,我将不胜感激。

谢谢!

---------------更新我添加了这个功能:

func managePhotoOrientation() -> UIImageOrientation {
    var currentDevice: UIDevice
    currentDevice = .current
    UIDevice.current.beginGeneratingDeviceOrientationNotifications()
    var deviceOrientation: UIDeviceOrientation
    deviceOrientation = currentDevice.orientation

    var imageOrientation: UIImageOrientation!

    if deviceOrientation == .portrait {
        imageOrientation = .up
        print("Device: Portrait")
    }else if (deviceOrientation == .landscapeLeft){
        imageOrientation = .left
        print("Device: LandscapeLeft")
    }else if (deviceOrientation == .landscapeRight){
        imageOrientation = .right
        CustomCamera.cameraPreviewLayer?.connection?.videoOrientation = .landscapeRight
        print("Device LandscapeRight")
    }else if (deviceOrientation == .portraitUpsideDown){
        imageOrientation = .down
        print("Device PortraitUpsideDown")
    }else{
       imageOrientation = .up
    }
    return imageOrientation
}
Run Code Online (Sandbox Code Playgroud)

并将我的扩展名更改为:

    extension FishCameraVC: AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        if let imageData = photo.fileDataRepresentation() {
            image = UIImage(data: imageData)
            let dataProvider  = CGDataProvider(data: imageData as CFData)
            let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)
            self.image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: imageOrientation!)
            performSegue(withIdentifier: "ShowTakenPhoto", sender: nil)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

图像以正确的方向显示在预览中,但是当我保存它时,它会变成纵向...

dr_*_*rto 6

我遇到了类似的问题,并通过根据拍摄的照片生成新图像来修复它:

UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
image.draw(in: CGRect(origin: .zero, size: image.size))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Run Code Online (Sandbox Code Playgroud)

显然,iOS 生成的图像元数据(包括方向)不完整,并且某些查看器(在我的例子中是 Chrome 和 Safari 浏览器)无法正确渲染图像。通过重新渲染,元数据似乎已为所有查看者正确设置。

请注意,1)在我的应用程序中,我还缩小了图像的尺寸(尽管我认为这不会改变效果),2)我通过其他方式捕获图像(即UIImagePickerController);不过,你可以尝试一下我的 hacky 修复。


ada*_*oto 5

您需要在调用 capturePhoto() 之前运行以下代码

if let photoOutputConnection = CustomCamera.photoOutput.connection(with: AVMediaType.video) {
    photoOutputConnection.videoOrientation = videoDeviceOrientation
}
Run Code Online (Sandbox Code Playgroud)

您可以使用 managePhotoOrientation() 函数来获取 videoDeviceOrientation。