gpt4 book ai didi

ios - 调用 `cgImageRepresentation()!.takeUnretainedValue()`后AVCapturePhoto逆时针旋转90

转载 作者:行者123 更新时间:2023-11-28 11:25:45 28 4
gpt4 key购买 nike

我正在使用 AVFoundation 在 iOS 上拍摄方形照片的应用程序。当我在 photoOutput(_:, didFinishProcessingPhoto:, error:) 中使用以下语句保存图像时,保存在我的相册中的图像方向正确。

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)
}
}

但是,当我将代码替换为以下代码以保存CGImage对象时,我发现我相册中保存的图像逆时针旋转了90。

func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
let image = photo.cgImageRepresentation()!.takeUnretainedValue()
UIImageWriteToSavedPhotosAlbum(UIImage(cgImage: image), nil, nil, nil)
}

这是我的照片捕获管道配置。

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()
}

我想知道是什么导致了这个问题?我该如何解决这个问题。

最佳答案

我的理解是,两种情况下的底层图像数据是相同的,显示上的差异是由于 photo.cgImageRepresentation() 中缺少元数据所致。照片应用了解图像元数据,并根据图像元数据中“方向”属性的值自动应用必要的旋转和/或镜像。

使用 PHPhotoLibrary 函数会生成带有嵌入元数据的图像副本。如 CGImagePropertyOrientation 中所述, iOS 以 .right 方向保存对象。但是,直接从 AVCapturePhoto 对象创建的 CGImage 不包含关联的元数据。

有几个潜在的修复(这些尚未经过测试,但应该有助于找到有效的解决方案):

  1. 使用从照片元数据中获得的方向创建 UIImage
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
let image = photo.cgImageRepresentation()!.takeUnretainedValue()
let orientation = CGImageProperyOrientation(rawValue: photo.metadata["Orientation"] as! UInt32)
var uiImage: UIImage!
if orientation == .right {
uiImage = UIImage(cgImage: image, scale: 1.0, orientation: .right)
} else {
uiImage = UIImage(cgImage: image)
}
UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil)
}
  1. 使用 CGImageDestinationImage I/O framework 中的 CGImageDestinationAddImageAndMetadata 函数保存带有元数据的 CGImage .

  2. 根据具体用例,可能需要显式旋转图像数据。可以找到如何执行此操作的示例 here .

关于ios - 调用 `cgImageRepresentation()!.takeUnretainedValue()`后AVCapturePhoto逆时针旋转90,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58224013/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com