I'm working on an app that take square pictures on iOS with AVFoundation
. When I save the image with the following statements in photoOutput(_:, didFinishProcessingPhoto:, error:)
, the image saved in my album have correct direction.
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
PHPhotoLibrary.requestAuthorization { status in
guard status == .authorized else { return }
PHPhotoLibrary.shared().performChanges({
let creationRequest = PHAssetCreationRequest.forAsset()
creationRequest.addResource(with: .photo, data: photo.fileDataRepresentation()!, options: nil)
}, completionHandler: nil)
}
}
However, when I replace the code with the following in order to save the CGImage
object, I found the image saved in my album was rotated by 90 counterclockwise.
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
let image = photo.cgImageRepresentation()!.takeUnretainedValue()
UIImageWriteToSavedPhotosAlbum(UIImage(cgImage: image), nil, nil, nil)
}
Here's my configuration of my photo capture pipeline.
private func initializeCapturePipeline() {
captureSession = AVCaptureSession()
captureSession?.sessionPreset = .photo
captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)
videoInput = try! AVCaptureDeviceInput(device: captureDevice!)
imageOutput = AVCapturePhotoOutput()
captureSession?.addInput(videoInput!)
captureSession?.addOutput(imageOutput!)
imageOutput?.connection(with: .video)?.videoOrientation = .portrait
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
previewLayer?.videoGravity = .resizeAspectFill
videoContainerView.layer.addSublayer(previewLayer!)
captureSession?.startRunning()
}
I wonder what is causing the problem? How could I fix this problem.