简体   繁体   English

Swift:在 swift 中应用过滤器时的 UIImage 方向问题

[英]Swift: UIImage orientation problem when applying filter in swift

I want to convert an image to grayscale by CIPhotoEffectNoir , but after using it, the image rotates.我想通过CIPhotoEffectNoir将图像转换为灰度,但使用它后,图像旋转。 I searched a lot but the answers can not solve my problem.我搜索了很多,但答案无法解决我的问题。

This is my code:这是我的代码:

    func grayscale(image: UIImage) -> UIImage? {
        let context = CIContext(options: nil)
        if let filter = CIFilter(name: "CIPhotoEffectNoir") {
            filter.setValue(CIImage(image: image), forKey: kCIInputImageKey)
            
            if let output = filter.outputImage {
                if let cgImage = context.createCGImage(output, from: output.extent) {
                    return UIImage(cgImage: cgImage)
                }
            }
        }
        return nil
    }

before:前:

在此处输入图片说明

after:后:

在此处输入图片说明

what I want:我想要的是:

在此处输入图片说明

When you create your new UIImage instance, don't forget to use the scale and orientaion values from the original UIImage.创建新的 UIImage 实例时,不要忘记使用原始 UIImage 中的scaleorientaion值。

return UIImage(
  cgImage: cgimg, 
  scale: image.scale, 
  orientation: image.imageOrientation)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM