Save image with the correct orientation - Swift & Core Image

ⅰ亾dé卋堺 提交于 2019-12-06 07:32:43

问题


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)
}

回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/28843045/save-image-with-the-correct-orientation-swift-core-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!