以正确的方向保存图像-Swift&核心形象 [英] Save image with the correct orientation - Swift & Core Image

查看:91
本文介绍了以正确的方向保存图像-Swift&核心形象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Swift 中的 Core Image 编辑照片,并且保存照片时出现问题。我没有以正确的方向保存它。
当我从照片库获取图片时,我将方向保存为UIImageOrientation变量,但是在将编辑后的照片保存到照片中之前,我不知道如何重新设置图书馆。有什么想法吗?

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?

保存方向:

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


推荐答案

代替使用 writeImageToSavedPhotosAlbum 元数据版本,可以使用:

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.

要满足Swift,您可以可能需要先进行类型转换:

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.

(正如您已经确认的那样,该解决方案确实在Swift中有效-我未经测试就从工作的Objective-C代码派生了它)

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

更新UIImage方向元数据吗?

强制UIImagePickerController以iOS纵向/尺寸拍摄照片

如何获得作者可可中的图片

从已选择的网址中获取URL。图像,iOS

小测试github上的项目,它从各种来源中挖掘出图像元数据(它是Objective-C,但原理是相同的。)。

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

这篇关于以正确的方向保存图像-Swift&核心形象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆