Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 946
Junchao Gu Avatar asked Jun 19 '15 02:06

Junchao Gu


2 Answers

- (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;
}
like image 64
oldrinmendez Avatar answered Oct 19 '22 03:10

oldrinmendez


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
}
like image 33
Nadeesha Lakmal Avatar answered Oct 19 '22 03:10

Nadeesha Lakmal