我知道有很多类似的问题,但是它们的解决方案对我不起作用。
注意: 图片是从互联网下载的。它并不是从 iPhone
的相机中拍摄的。
我有一个 UIImage
。为了进行一些图像处理操作,我使用 Metal
并在 MTKView
中呈现图像。因此,我将图像转换为 CIImage
。在修改图像后,我将其转换回 CGImage
,然后再转换回 UIImage
并保存它。
结果,保存的图像方向是错误的。
我不确定在哪个步骤中失去了方向(当从 UIImage
转换为添加到 MTKView
的 CIImage
时,还是当从 CIImage
转换为 CGImage
然后再转换为 UIImage
以保存它时)。因为我不确定,在下面针对每个步骤提供了我尝试过的所有内容:
将 UIImage
转换为 CIImage
:
最初,我是通过以下方式简单地转换图像的:
let let ciImage = CIImage(image: image)
然后我尝试使用以下方法:
let ciImage = CIImage(image: image)?.oriented(forExifOrientation: imageOrientationToTiffOrientation(value: image.imageOrientation))
以下是方法
imageOrientationToTiffOrientation
的实现(我在这里找到它):func imageOrientationToTiffOrientation(value: UIImageOrientation) -> Int32
{
switch (value)
{
case .up:
return 1
case .down:
return 3
case .left:
return 8
case .right:
return 6
case .upMirrored:
return 2
case .downMirrored:
return 4
case .leftMirrored:
return 5
case .rightMirrored:
return 7
}
}
将CIImage
转换为CGImage
,然后再转换为UIImage
:
我像往常一样将CIImage
转换为CGImage
:
let cgImage = context?.createCGImage(ciImage, from: ciImage.extent)
然后我通过以下方式将cgImage
转换为UIImage
(imageToSave
):
let imageToSave = UIImage(cgImage: cgImage, scale: image.scale, orientation: imageOrientation)
imageOrientation
和 image.scale
是原始图像的方向和比例。因此,保存的图像仍然具有错误的方向。
有趣的是,当我打印这些图像方向的原始值时,它们都是相同的
0
,即.up
,但是在保存后,方向就变成了错误的。我很困惑为什么会发生这种情况。如果您对如何解决此问题有任何建议,我将不胜感激。
CIContext().writeJPEGRepresentation
。 - undefined