UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 67: Instafilter image orientation

Forums > 100 Days of SwiftUI

After completing the Instafilter project I noticed some of the images were appearing upside-down. After a lot of searching I found one line that fixes it.

Replace this:

let uiImage = UIImage(cgImage: cgimg)

With this:

let uiImage = UIImage(cgImage: cgimg, scale: 1, orientation: inputImage?.imageOrientation ?? .up)

When the initial image is loaded as a UIImage it comes with an orientation property. A CIImage is created from the UIImage and then a CGImage is created from the CIImage. I'm not sure which step loses the image orientation property but it can be added back in when converting to a UIImage.

It might make more sense to keep this orientation throughout the process, especially if any of your steps might look different based on orientation. I think this would be the first step:

let beginImage = CIImage(image: inputImage, options: [CIImageOption.applyOrientationProperty:true])

Now I think I just need to set the orientation of the CG image.

4      

Hi Ryan

See my code here where I've used a "common extension" to transform the UIImage.Orientation

extension CGImagePropertyOrientation {
    init(_ uiOrientation: UIImage.Orientation) {
        switch uiOrientation {
            case .up: self = .up
            case .upMirrored: self = .upMirrored
            case .down: self = .down
            case .downMirrored: self = .downMirrored
            case .left: self = .left
            case .leftMirrored: self = .leftMirrored
            case .right: self = .right
            case .rightMirrored: self = .rightMirrored
            @unknown default:
                fatalError("Unknown uiOrientation \(uiOrientation)")
        }
    }
}

and use it in the loadImage() function as follows:

        let beginImage : CIImage
        if let ciImage = inputImage.ciImage {
            beginImage = ciImage
        }
        else {
            beginImage = CIImage(cgImage: inputImage.cgImage!).oriented(CGImagePropertyOrientation(inputImage.imageOrientation))
        }

I hope this works for you too.

regards Philipp

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.