UIImageOrientation与相机

时间:2017-02-01 06:46:19

标签: ios swift3 avfoundation xcode8 uiimageorientation

这是我的相机的代码,将前置摄像头更换为后置摄像头,如果我用后置摄像头拍照,照片的方向是好的(原始),但如果我用前面拍照相机拍摄的图像方向不正确。

class TakeSelfieViewController: UIViewController, AVCapturePhotoCaptureDelegate {

var captureSession = AVCaptureSession()
var photoOutput = AVCapturePhotoOutput()
var previewLayer : AVCaptureVideoPreviewLayer?
var captureDevice : AVCaptureDevice?

var sessionOutputSetting = AVCapturePhotoSettings(format: [AVVideoCodecKey:AVVideoCodecJPEG])

var toggle = false

@IBOutlet weak var cameraView: UIView!
@IBOutlet weak var tempImageView: UIImageView!
@IBOutlet weak var adorButton: UIButton!

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    previewLayer?.frame = cameraView.bounds

    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = adorButton.bounds
    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    adorButton.addSubview(blurEffectView)

}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    pickCamera(which: toggle)

}

func pickCamera(which: Bool) {

    if (which == true) {

        let deviceDescovery = AVCaptureDeviceDiscoverySession(deviceTypes: [AVCaptureDeviceType.builtInDualCamera, AVCaptureDeviceType.builtInTelephotoCamera,AVCaptureDeviceType.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: AVCaptureDevicePosition.back)

        print("back camera")

        startCamera(deviceDesc: deviceDescovery!)

        toggle = true

    } else if (which == false) {

        let deviceDescovery = AVCaptureDeviceDiscoverySession(deviceTypes: [AVCaptureDeviceType.builtInDualCamera, AVCaptureDeviceType.builtInTelephotoCamera,AVCaptureDeviceType.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: AVCaptureDevicePosition.front)

        print("front camera")

        startCamera(deviceDesc: deviceDescovery!)

        toggle = false

    }

}


func startCamera(deviceDesc: AVCaptureDeviceDiscoverySession!) {

    for device in (deviceDesc.devices)! {


        if device.position == AVCaptureDevicePosition.back {

            do {

                let input = try AVCaptureDeviceInput(device: device)
                if captureSession.canAddInput(input) {
                    captureSession.addInput(input)

                    if captureSession.canAddOutput(photoOutput) {
                        captureSession.addOutput(photoOutput)


                        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                        previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
                        previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait


                        cameraView.layer.addSublayer(previewLayer!)
                        captureSession.startRunning()
                        print("ADD Back")

                    } else { print("Cannot add input - back") }

                }

            } catch {

                print("Error")

            }

        } else if (device.position == AVCaptureDevicePosition.front) {

            do {

                let input = try AVCaptureDeviceInput(device: device)
                print(input)
                if captureSession.canAddInput(input) {

                    captureSession.addInput(input)

                    if captureSession.canAddOutput(photoOutput) {
                        captureSession.addOutput(photoOutput)


                        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                        previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
                        previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait


                        cameraView.layer.addSublayer(previewLayer!)
                        captureSession.startRunning()
                        print("ADD Front")

                }

                } else { print("Cannot add input - front") }

            } catch {

                print(error)

            }
        }
    }
}

func didPressTakePhoto() {
    if let videoConnection = photoOutput.connection(withMediaType: AVMediaTypeVideo) {
        videoConnection.videoOrientation = AVCaptureVideoOrientation.portrait
        let settings = AVCapturePhotoSettings(format: [AVVideoCodecKey : AVVideoCodecJPEG])
        photoOutput.capturePhoto(with: settings, delegate: self)

    }
}

func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {

    let imageData = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: photoSampleBuffer!, previewPhotoSampleBuffer: previewPhotoSampleBuffer)
    let dataProvider = CGDataProvider(data: imageData as! CFData)
    let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)

    let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.right)
    self.tempImageView.image = image
    self.tempImageView.isHidden = false
    self.yellowButton.isHidden = true
    self.toggleAction.isHidden = true
    self.adorButton.isHidden = true
    print("Hola")
}

var didTakePhoto = Bool()

@IBOutlet weak var yellowButton: UIButton!
@IBOutlet weak var toggleAction: UIButton!

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if didTakePhoto {
        tempImageView.isHidden = true
        yellowButton.isHidden = false
        toggleAction.isHidden = false
        adorButton.isHidden = false
        didTakePhoto = false
        print("")

    }
}

@IBAction func yellowPressed(_ sender: UIButton) {
    captureSession.startRunning()
    didTakePhoto = true
    didPressTakePhoto()
    print("")
}

@IBAction func toggleCamera(_ sender: Any) {

    if (toggle == false) {

        print("Changing to back camera")

        let currentCameraInput: AVCaptureInput = captureSession.inputs[0] as! AVCaptureInput

        captureSession.removeInput(currentCameraInput)

        toggle = true

        pickCamera(which: toggle)

    } else if (toggle == true) {

        print("Changing to front camera")

        let currentCameraInput: AVCaptureInput = captureSession.inputs[0] as! AVCaptureInput

        captureSession.removeInput(currentCameraInput)

        toggle = false

        pickCamera(which: toggle)

    }

}

override var prefersStatusBarHidden: Bool {

    return true

}
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

使用前置摄像头拍摄的图像是镜像的,当您对图片进行故障排除时,图像方向在其EXIF词典中进行,或者在元数据字典内传递。
大多数情况下,当您将其作为JPG或PNG传递时,如果您不直接处理此值,则不会考虑此值。 如果你在风景中拍照,你应该会遇到类似的问题 在你的捕捉方法中,当你应该处理它时,似乎你正在强制定向到固定值 很久以前我写了这个post,我认为它可以帮助你检测你的问题,即使大多数是用objC编写的。我写了一些关于相机输出方向的实验。