0

In swift 3.2 app I allow the user to either take a photo or select one from the phones gallery.

I show the image in the app and its right side up. I save the image to the directory by converting the png to data using the UIImagePNGRepresentation() method.

Upon retrieving the image its upside down. As far as I can tell I am not rotating the image anywhere.

IOS Guy
  • 11
  • When I run the sam code using the simulator on my Mac an selecting one of the 5 default images it works fine. – IOS Guy Oct 16 '17 at 15:22
  • It would be nice to show the code you are currently using. That's what is meant when someone asks "what have you tried". –  Oct 16 '17 at 16:00
  • Try using jpeg data instead on png data when saving imade to directory image.jpegData(compressionQuality: 1.0)?.write(to: fileURL) – Timchang Wuyep May 16 '22 at 11:55

2 Answers2

2

I had also faced the same issue. The only fix that popped out in my mind was to check if the orientation of the image is upright. If it's not upright, we need to get the correct image from the graphics context.

You can write an extension to fix image orientation as follows: (source: here)

extension UIImage {
    func fixOrientation() -> UIImage {
        if self.imageOrientation == UIImageOrientation.up {
            return self
        }

        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
        let normalizedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return normalizedImage;
    }
}

then call the method once you take pic from camera.

 chosenImage = chosenImage.fixOrientation()
Rikesh Subedi
  • 1,755
  • 22
  • 21
0

Mobile phones save images captured with the camera in the orientation that corresponds to how the CCD sensor returns the image data to make their life easier. It dates back to the time when phones had insufficient memory to rotate the image. Additionally, they save meta information about what orientation the image was saved in so it can be properl displayed.

I don't know how you display the image in your app but obviously you use code that knows about this.

Before using UIImagePNGRepresentation you have to fix the rotation of your image. Rikesh Subedi's code should work. But there's plenty more on StackOverflow.

Alternatively, you can save it as a JPEG. Unlike PNG, JPEG supports the meta information for storing the image's orientation.

Codo
  • 75,595
  • 17
  • 168
  • 206