I know there are tons of questions like this but their solutions don't work for me.
NOTE: The image is downloaded from the Internet. It isn't taken from iPhone
's camera.
I have a UIImage
. To do some image processing operations I use Metal
and present the image in a MTKView
. So, I convert the image into a CIImage
.
After doing all the modifications to the image I convert it back into CGImage
and then into UIImage
and save it.
As a result the saved image's orientation is wrong.
I'm not sure in which step it looses its orientation (when converting from UIImage
into CIImage
for adding to MTKView
, or while converting from CIImage
into CGImage
and then into UIImage
to save it). Because I'm not sure, bellow I provide everything I've tried for each steps:
For converting from UIImage
into CIImage
:
Initially I was simply converting the image in this way:
let let ciImage = CIImage(image: image)
Then I tried to use the following way:
let ciImage = CIImage(image: image)?.oriented(forExifOrientation: imageOrientationToTiffOrientation(value: image.imageOrientation))
Here is the method imageOrientationToTiffOrientation
's implementation (I found it here):
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
}
}
For converting from CIImage
into CGImage
and then into UIImage
:
I convert CIImage
into CGImage
as usual:
let cgImage = context?.createCGImage(ciImage, from: ciImage.extent)
Then I convert cgImage
into UIImage
(imageToSave
) this way:
let imageToSave = UIImage(cgImage: cgImage, scale: image.scale, orientation: imageOrientation)
imageOrientation
and image.scale
are the original image's orientation and scale.
As a result, the saved image still has a wrong orientatio.
Interestingly when I print those images orientations raw values, they are the same 0
which is the .up
, however as I said, after saving, the orientation is wrong.
I'm quite confused why is this happening. If you have any suggestions about how to fix this, I would appreciate your help.