2

I'm learning how to use UIImagePickerController and got stuck with a problem using UIImagePickerController.sourceType = .camera.

What my app is supposed to do is:

  1. to allow a user to take a photo using the system view controller mentioned above
  2. then convert this image using UIImage.pngData(_:)
  3. save this data to an appropriate struct field (doesn't matter which one, in that case)
  4. use data saved to the structure to make up an image and set this image as a UIButton foreground image

When i'm doing so (following App Development with Swift book's example project) image appears to be rotated 90 degrees for some reason, which I'd like to know.

I've tried to create additional UIImageView and set its image property before converting UIImage to pngData, and it appeared normally (see 2nd screenshot).

When choosing a photo from the photo library problem does not occur in any of the cases (before-after converting).

So I suppose, that pngData is somehow losing photo-orientation information? Or I've messed somewhere else, perhaps.

Here are screenshots from my app, so you can see how original taken photo looks, and how it looks in-app (above labels - UIButton, below - test UIImageView). Nevermind text :)

How user sees taken photo How it looks in-app

Jawad Ali
  • 13,556
  • 3
  • 32
  • 49

1 Answers1

4

If you save UIImage as a JPEG, this will set the rotation flag.

PNGs do not support a rotation flag, so if you save a UIImage as a PNG, it will be rotated incorrectly and not have a flag set to fix it. So if you want PNGs you must rotate them yourself.

let jpgData = downloadedImage.jpegData(compressionQuality: 1)

To get rotated image you need to draw that.. you can use following extension

extension UIImage {
    func rotateImage()-> UIImage?  {
        if (self.imageOrientation == UIImage.Orientation.up ) {
            return self
        }
        UIGraphicsBeginImageContext(self.size)
        self.draw(in: CGRect(origin: CGPoint.zero, size: self.size))
       let copy = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return copy
    }
}

How to use

let rotatedImage =  downloadedImage.rotateImage()
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49