iOS UIImage: set image orientation without rotating the image itself
Asked Answered
E

2

5

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?

Emie answered 19/6, 2015 at 2:53 Comment(0)
A
10
- (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;
}
Automatism answered 19/6, 2015 at 6:25 Comment(0)
O
8

swift version of oldrinmendez answer

func removeRotationForImage(image: UIImage) -> UIImage {
    if image.imageOrientation == UIImageOrientation.Up {
        return image
    }

    UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
    image.drawInRect(CGRect(origin: CGPoint(x: 0, y: 0), size: image.size))
    let normalizedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return normalizedImage
}
Os answered 20/1, 2017 at 19:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.