【发布时间】:2022-01-14 11:43:30
【问题描述】:
在我用 Swift 编写的 iOS 应用上,我需要拍照并将它们保存在图库中;作为Apple文档,如果手机是纵向的,所有照片都是横向拍摄的;如果我们按原样保存图片,它将旋转 90° 保存。
问题:保存图片时如何正确管理设备方向?
感谢一些搜索,我使用了这个解决方案:
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
// ...error handling here
guard let imageData = photo.fileDataRepresentation(with: self) else {
NSLog("Fail to convert pixel buffer")
return
}
// Save image to gallery here
}
我的班级是AVCapturePhotoFileDataRepresentationCustomizer 代表,所以:
func replacementMetadata(for photo: AVCapturePhoto) -> [String : Any]? {
var properties = photo.metadata
// Image orientation
properties[kCGImagePropertyOrientation as String] = CGImagePropertyOrientation.right
let exifData = NSMutableDictionary(dictionary: properties[kCGImagePropertyExifDictionary as String] as! NSDictionary)
let xDimension = exifData[kCGImagePropertyExifPixelYDimension as String]
let yDimension = exifData[kCGImagePropertyExifPixelXDimension as String]
if xDimension != nil && yDimension != nil {
exifData[kCGImagePropertyExifPixelXDimension as String] = xDimension
exifData[kCGImagePropertyExifPixelYDimension as String] = yDimension
properties[kCGImagePropertyExifDictionary as String] = exifData
}
return properties
}
因为图像是纵向拍摄的,所以方向是 .right,我在搜索中读到 exif 数据中的 X 和 Y 尺寸也应该交换。
不幸的是,一切都没有结果:使用 exif 资源管理器图像方向检查保存的图像仍然是 0=未知值,X 和 Y 仍为原始设置。
我确定数据设置和写入正确,因为:
-
断点
return properties强调方向标签设置正确;此外,如果标签未正确设置或未知,则应用程序崩溃... -
在同一个
replacementMetadata函数中,我还设置了 GPS 数据(为了简单起见,我在这里剪掉了它!),我写了一些测试值(如标题 = 101),这些数据在最终图像元数据中正确报告。
所以我的问题仍然存在......感谢您使用代码 sn-ps 或文档为我指明正确的方向。
【问题讨论】:
标签: ios swift exif phphotolibrary