WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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.


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


Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

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.