Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Losing image orientation while converting an image to CGImage

I'm facing an image orientation issue when cropping a square portion of an image out of a rectangular original image. When image is in landscape, it's fine. But when it is in portrait, it seems that the image orientation is not preserved, which result in an image with wrong orientation AND bad crop:

 func cropImage(cropRectangleCoordinates: CGRect) {

        let croppedImage = originalImage

        let finalCroppedImage : CGImageRef = CGImageCreateWithImageInRect(croppedImage.CGImage, cropRectangleCoordinates)

        finalImage =  UIImage(CGImage: finalCroppedImage)!


    }

I think the problem is with croppedImage.CGImage. Here the image gets converted to CGImage, but it seems not to preserve the orientation. It's easy to preserve orientation by using UIImage only, but to make the crop, image needs to be temporarily CGImage and this is the problem. Even if I reorient the image when converting back to UIImage, it might be in the correct orientation but the damage is already done when cropping CGImage.

This is a swift question, so please answer in swift, as the solution can be different in Objective-C.

like image 750
Robert Brax Avatar asked Feb 12 '15 13:02

Robert Brax


People also ask

How do I change the orientation of a picture in Swift?

Basic Swift Code for iOS AppsStep 1 − Open Xcode→SingleViewApplication→name it RotateImage. Step 2 − Open Main. storyboard, add UIImageView and add 2 buttons as shown below name them ROTATE BY 90 DEGREES AND ROTATE BY 45 DEGREES. Add some sample images to UIImage View.

What does image orientation mean?

Image Display Orientation. Display orientation refers to whether row number increases upward or downward. The orientation also affects the sense in which angles are measured. This is important to know because, as described below, images in different formats are displayed in different directions.


1 Answers

SWIFT 3:

convert rotated cgImage to UIImage by this method

UIImage(cgImage:croppedCGImage, scale:originalImage.scale, orientation:originalImage.imageOrientation)

Source @David Berry answer

like image 64
Adnan Yusuf Avatar answered Oct 05 '22 01:10

Adnan Yusuf