iOS PNG Image rotated 90 degrees

Boeckm picture Boeckm · Apr 25, 2012 · Viewed 27.7k times · Source

In my iOS application I'm writing, I deal with PNGs because I deal with the alpha channel. For some reason, I can load a PNG into my imageView just fine, but when it comes time to either copy the image out of my application (onto the PasteBoard) or save the image to my camera roll, the image rotates 90 degrees.

I've searched everywhere on this, and one of the things I learned is that if I used JPEGs, I wouldn't have this problem (it sounds), due to the EXIF information.

My app has full copy/paste functionality, and here's the kicker (I'll write this in steps so it is easier to follow):

  1. Go to my camera roll and copy an image
  2. Go into my app and press "Paste", image pastes just fine, and I can do that all day
  3. Click the copy function I implemented, and then click "Paste", and the image pastes but is rotated.

I am 100% sure my copy and paste code isn't what is wrong here, because if I go back to Step 2 above, and click "save", the photo saves to my library but it is rotated 90 degrees!

What is even more strange is that it seems to work fine with images downloaded from the internet, but is very hit or miss with images I manually took with the phone. Some it works, some it doesn't...

Does anybody have any thoughts on this? Any possible work arounds I can use? I'm pretty confident in the code being it works for about 75% of my images. I can post the code upon request though.

Answer

Tom J picture Tom J · Oct 27, 2014

For those that want a Swift solution, create an extension of UIImage and add the following method:

func correctlyOrientedImage() -> UIImage {
    if self.imageOrientation == .up {
        return self
    }

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

    return normalizedImage ?? self;
}