The title to this question should be rather clear. The code below performs a cropping operation and then displays the new cropped photo in an Image View. The problem is that the image, once cropped, is displayed with a different orientation than the original source image. Why is that? And what should I do about it?
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self.popoverController dismissPopoverAnimated:true];
NSString *mediaType = [info
objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *image = [info
objectForKey:UIImagePickerControllerOriginalImage];
CGRect rect = CGRectMake(0, ((image.size.height - image.size.width) / 2), image.size.width, image.size.width);
CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
CGRect smallBounds = CGRectMake(rect.origin.x, rect.origin.y, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));
UIGraphicsBeginImageContext(smallBounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, smallBounds, subImageRef);
croppedImage = [UIImage imageWithCGImage:subImageRef];
UIGraphicsEndImageContext();
imageView.image = croppedImage;
*EDIT
Based on the comments suggesting that root cause of the issue is the removal of the EXIF tag I attempted to correct the orientation with the following code. This still doesn't fix the problem but I think it is a step in the right direction. Perhaps it will help someone to propose a new answer to the question.
if (image.imageOrientation == UIImageOrientationLeft) {
NSLog(@"left");
CGContextRotateCTM (context, radians(90));
} else if (image.imageOrientation == UIImageOrientationRight) {
NSLog(@"right");
CGContextRotateCTM (context, radians(-90));
} else if (image.imageOrientation == UIImageOrientationUp) {
NSLog(@"up");
// NOTHING
} else if (image.imageOrientation == UIImageOrientationDown) {
NSLog(@"down");
CGContextRotateCTM (context, radians(-180.));
}