Save image with the correct orientation - Swift & Core Image
Asked Answered
A

2

3

I'm using Core Image in Swift for editing photos and I have a problem when I save the photo. I'm not saving it with correct orientation. When I get the picture from the Photo Library I'm saving the orientation in a variable as UIImageOrientation but I don't know how to set it back before saving the edited photo to the Photo Library. Any ideas how?

Saving the orientation:

var orientation: UIImageOrientation = .Up
orientation = gotImage.imageOrientation

Saving the edited photo to the Photo Library:

@IBAction func savePhoto(sender: UIBarButtonItem) {
    let originalImageSize = CIImage(image:gotImage)
    filter.setValue(originalImageSize, forKey: kCIInputImageKey)
    // 1
    let imageToSave = filter.outputImage

    // 2
    let softwareContext = CIContext(options:[kCIContextUseSoftwareRenderer: true])

    // 3
    let cgimg = softwareContext.createCGImage(imageToSave, fromRect:imageToSave.extent())

    // 4
    let library = ALAssetsLibrary()
    library.writeImageToSavedPhotosAlbum(cgimg,
        metadata:imageToSave.properties(),
        completionBlock:nil)
}
Arreola answered 3/3, 2015 at 22:17 Comment(0)
D
2

Instead of using the metadata version of writeImageToSavedPhotosAlbum, you can use :

library.writeImageToSavedPhotosAlbum(
                cgimg,
                orientation: orientation,
                completionBlock:nil)

then you can pass in the orientation directly.

To satisfy Swift, you may need to typecast it first:

var orientation : ALAssetOrientation = ALAssetOrientation(rawValue:           
                                    gotImage.imageOrientation.rawValue)!

As per my somewhat inconclusive answer here.

(As you have confirmed, this solution does indeed work in Swift - I derived it, untested, from working Objective-C code)

If you are interested in manipulating other information from image metadata, here are a few related answers I provided to other questions...

Updating UIImage orientation metaData?
Force UIImagePickerController to take photo in portrait orientation/dimensions iOS
How to get author of image in cocoa
Getting a URL from (to) a "picked" image, iOS

And a small test project on github that digs out image metadata from various sources (it's objective-C, but the principles are the same).

Driskell answered 4/3, 2015 at 23:25 Comment(1)
ALAssetsLibrary()is deprecated in iOS 9, now you have to use PHPhotoLibraryNeille
N
1

You are calling writeImageToSavedPhotosAlbum:metadata:completionBlock:... The docs on that method say:

You must specify the orientation key in the metadata dictionary to preserve the orientation of the image.

Numismatist answered 4/3, 2015 at 1:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.