Search code examples
iosimageuiimageuiimageorientation

iOS UIImage: set image orientation without rotating the image itself


I am using AVCapture+camera portrait mode to capture an image. when I display the captured image, it is fine--looks fine. But when I convert to jpeg representation and then convert to base64 string to server and server stored it, it is "rotated" already.

So I checked the image orientation before sending to server: it is UIImageOrientation.Right(so is there any way to capture an image using portrait mode but the captured image orientation is up? well, I doubt that after some digging). After the server got the image, it did not do anything, just ignored the metadata about orientation I guess.

since the image I captured looks fine, I want just preserve how the image look like. However, I want to set the image orientation to be up. if I just set the image orientation, the image does not look right anymore.

So is there a way to set the orientation without causing the image to be rotated or after setting the orientation to be up, how to I keep the orientation but rotate the actual image to make it look right?


Solution

  • - (UIImage *)removeRotationForImage:(UIImage*)image {
       if (image.imageOrientation == UIImageOrientationUp) return image;
    
       UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
       [image drawInRect:(CGRect){0, 0, image.size}];
       UIImage *normalizedImage =  UIGraphicsGetImageFromCurrentImageContext();
       UIGraphicsEndImageContext();
       return normalizedImage;
    }