如何将图像方向应用于CIImage?

问题描述 投票:0回答:1

我试着用CIFilter合成两张图片,但我不能正确处理图片的方向。

在下面的例子中,我拍摄了相同的场景,但是手机有2个不同的方向(第一张图片的音量键在上面,第二张图片的音量键在下面)。在下面的截图中,第一张图片显示在顶部,第二张图片显示在中间。我验证了这2个图像的方向是不同的(参考下面的截图) print 调用)。)

SwiftUI正确处理了图像的方向。如果我现在使用CIFilter(第三张图片)来合成这两张图片,图片的方向没有被考虑进去,合成的效果也不是我想要的(我想让两个杯子并排)。

这显然不是bug。但是,如何在应用合成CIFIlter之前根据各自的方向旋转输入图像?标准的方法是什么?

谢谢您的帮助。

下面是这个简单例子对应的代码。

import SwiftUI

struct ContentView: View {

    @State var input1 = UIImage(named: "image1.jpg")
    @State var input2 = UIImage(named: "image2.jpg")
    @State var output : UIImage?

    var body: some View {
        VStack {

            Image(uiImage: input1!)
                .resizable()
                .scaledToFit()

            Image(uiImage: input2!)
                .resizable()
                .scaledToFit()

            if output != nil {
                Image(uiImage: output!)
                    .resizable()
                    .scaledToFit()
            }

        }
        .onAppear(){
            self.compose()
        }
    }

    func compose() {

        print("Orientation of input1: \(input1!.imageOrientation.rawValue)")
        print("Orientation of input2: \(input2!.imageOrientation.rawValue)")

        let ciContext = CIContext(options: nil)

        let ciInput1 = CIImage(image: input1!)
        let ciInput2 = CIImage(image: input2!)

        let filter = CIFilter(name: "CILinearDodgeBlendMode")!
        filter.setValue(ciInput1, forKey: "inputImage")
        filter.setValue(ciInput2, forKey: "inputBackgroundImage")

        let ciOutput = filter.value(forKey: kCIOutputImageKey) as! CIImage

        let cgOutput = ciContext.createCGImage(ciOutput, from: ciOutput.extent)!

        output = UIImage(cgImage: cgOutput)
    }
}

这是对应的截图

enter image description here

swift cifilter
1个回答
1
投票

你可以告诉Core Image在加载时把图像的方向考虑进去。

let ciInput1 = CIImage(image: input1!, options: [.applyOrientationProperty: true])
let ciInput2 = CIImage(image: input2!, options: [.applyOrientationProperty: true])

编辑。

因此,似乎上述方法只适用于从URL或数据加载图像时,而不是从... UIImage.

然而,你可以自己应用的方向,。这里有一个方便的扩展。

extension UIImage.Orientation {
    var exifOrientation: Int32 {
        switch self {
            case .up: return 1
            case .down: return 3
            case .left: return 8
            case .right: return 6
            case .upMirrored: return 2
            case .downMirrored: return 4
            case .leftMirrored: return 5
            case .rightMirrored: return 7
        }
    }
}

然后你可以像这样变换图像

let ciInput1 = CIImage(image: input1!).oriented(forExifOrientation: image1.imageOrientation.exifOrientation)
let ciInput2 = CIImage(image: input2!).oriented(forExifOrientation: image2.imageOrientation.exifOrientation)
© www.soinside.com 2019 - 2024. All rights reserved.