I'm building an app using RubyMotion. When I take picture then it all looks good. However when the picture is posted on web then the orientation of the picture is different.
UIImage and UIImageOrientation
UIImage in iOS has a property called UIImageOrientation. Image orientation affects the way the image data is displayed when drawn. The api docs mention that by default, images are displayed in the
up orientation. However, if the image has associated metadata (such as EXIF information), then this property contains the orientation indicated by that metadata.
After using UIImagePickerController to take an image using the iPhone camera, I was using BubbleWrap to send the image to a webserver. When the image is taken in landscape/portrait mode, then the image appeared fine when it is viewed in the browser. But, when the image is sent back via api and is shown on the iphone, the image is rotated by 90 degrees if the image is taken in portrait mode. In exif metadata, iOS incorrectly sets the orientation to UIImageOrientationRight .
Here is how I fixed the image orientation issue:
1if image.imageOrientation == UIImageOrientationUp 2 return_image = image 3else 4 UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale) 5 image.drawInRect([[0,0], image.size]) 6 normalized_image = UIImage.UIGraphicsGetImageFromCurrentImageContext 7 UIGraphicsEndImageContext() 8 return_image = normalized_image 9end
First, we are checking the image orientation of the image we have in hand. If the image orientation is UIImageOrientationUp, we don't have to change anything. Otherwise we are redrawing the image and returning the normalized image.