We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.
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 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:
if image.imageOrientation == UIImageOrientationUp return_image = image else UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale) image.drawInRect([[0,0], image.size]) normalized_image = UIImage.UIGraphicsGetImageFromCurrentImageContext UIGraphicsEndImageContext() return_image = normalized_image end
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.