Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImagePNGRepresentation issues? / Images rotated by 90 degrees

I want to load images from UIImagePickerController, then save the selected photo to my app's document directory.

UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; NSData *data1 = UIImagePNGRepresentation(image);  NSString *fileName = "1.png"; NSString *path = //get Document path, then add fileName BOOL succ = [data1 writeToFile:path atomically:YES]; 

but after I save the image to my document, I found that, the image was rotated 90 degree, then I change the method UIImagePNGRepresentation to UIImageJPEGRepresentation, this time it's fine, anyone know what's the problem?

like image 498
disorderdev Avatar asked Aug 24 '10 07:08

disorderdev


2 Answers

I had the same problem and just figured out the reason: starting with iOS 4.0 when the camera takes a photo it does not rotate it before saving, it simply sets a rotation flag in the EXIF data of the JPEG.

If you save a UIImage as a JPEG, it will set the rotation flag.

PNGs do not support a rotation flag, so if you save a UIImage as a PNG, it will be rotated incorrectly and not have a flag set to fix it. So if you want PNGs you must rotate them yourself.

I would call this a bug in the PNG saving function but that's just an opinion (they should at least warn you about this).

like image 160
jasongregori Avatar answered Sep 28 '22 10:09

jasongregori


Please try this.

func rotateImage(image: UIImage) -> UIImage? {     if image.imageOrientation == UIImage.Orientation.up {         return image /// already upright, no need for changes     }     UIGraphicsBeginImageContext(image.size)     image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))     let copy = UIGraphicsGetImageFromCurrentImageContext()     UIGraphicsEndImageContext()     return copy } 

Happy coding :)

like image 36
Stefan Avatar answered Sep 28 '22 08:09

Stefan