在我用Swift编写的iOS应用程序中,我需要拍照并将其保存在画廊中;作为苹果文档,所有的照片都采取了横向也如果手机是在纵向;如果我们按原样保存图片,它将被旋转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
delegate,所以:
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
上的断点强调方向标记设置正确;此外,如果标签未正确设置或未知,则应用程序崩溃……
1.在相同的replacementMetadata
函数中,我还设置了GPS数据(为了简单起见,我在这里将其删除!),我写了一些测试值(如heading = 101),这些数据在最终的图像元数据中正确报告。
所以我的问题是...感谢您用代码片段或文档为我指明了正确的方向。
3条答案
按热度按时间jtjikinw1#
您可以通过设置
AVCapturePhotoOutput
的videoOrientation
将拍摄方向设置为任何您喜欢的方向。要使其与当前设备方向相匹配,您可以使用
UIDevice.current.orientation
手动转换为AVCaptureVideoOrientation
。字符串
从
UIDeviceOrientation
转换为AVCaptureVideoOrientation
:型
sdnqo3pr2#
字符串
在您的文件中有相机代码:
型
当摄像机处于活动状态时,开始测量方向。
型
不使用摄像机时停止测量方向。
型
最后,在调用capturePhoto之前添加一行代码(使用:设置,委派:self)
型
qnyhuwrf3#
字符串