【问题标题】:Converting UIImage to CIImage Returns nil将 UIImage 转换为 CIImage 返回 nil
【发布时间】:2017-08-15 03:38:27
【问题描述】:

我正在尝试将 UIImage 从 imageView 转换为 CIImage 以过滤它。但是,我无法让 CIImage 具有值。

以最简单的形式,这是我正在尝试的:

let ciInput = CIImage(image: imageView.image!)

但 ciInput 总是为零。 我也试过了

let ciInput = CIImage(cgImage: imageView.image!.cgImage)

但也返回 nil。

(imageView.image 不是 nil,但 imageView.image!.cgImageimageView.image!.ciImage 都是 nil)

我需要将UIImageimageView 转换为有效的CIImage。任何帮助表示赞赏,谢谢!

编辑:这是完整的功能代码

func makeWhiteTransparent(imageView: UIImageView) {

    let invertFilter = CIFilter(name: "CIColorInvert")
    let ciContext = CIContext(options: nil)

    let ciInput = CIImage(image: imageView.image!) //This is nil
    invertFilter?.setValue(ciInput, forKey: "inputImage")

    let ciOutput = invertFilter?.outputImage
    let cgImage = ciContext.createCGImage(ciOutput!, from: (ciOutput?.extent)!)

    imageView.image = UIImage(cgImage: cgImage!)
}

当运行这个函数时,我在最后一行得到一个致命的 unwrapping nil 错误。使用调试器,我发现 ciInput 是 nil,它不应该是。

编辑 2: 调用makeWhiteTransparent前imageView上的图片是使用该函数生成的二维码:

func generateQRCode(from string: String) -> UIImage? {
    let data = string.data(using: String.Encoding.ascii)

    if let filter = CIFilter(name: "CIQRCodeGenerator") {
        filter.setValue(data, forKey: "inputMessage")

        let transform = CGAffineTransform(scaleX: 12, y: 12)

        if let output = filter.outputImage?.applying(transform) {
            return UIImage(ciImage: output)
        }
    }

    return nil
}

【问题讨论】:

  • imageView.image 最初是如何创建的?如果你添加了一行代码let uiImage = imageView.image 会发生什么?最后,请注意您正在强制展开 imageView.image。在我看来,您没有发布足够的代码。
  • 你是如何在imageView 中实例化UIImage 的?
  • 你怎么知道CIImage是nil?请从头到尾向我们展示如何重现此问题,从图像开始,图像视图,图像如何进入图像视图,您的代码在哪里运行,以及您如何得出ciInputnil.
  • 我添加了整个函数以获得更多细节,并标记了哪个变量为 nil。 nil 变量 ciInput 最终会导致“unexpectedly found nil...”错误
  • 嗯。我可能会建议进行一些小的更改,但这段代码对我来说是有效的。我想知道这张图片是否有什么特别之处?

标签: swift uiimage ciimage


【解决方案1】:

所以问题出在我的二维码生成上。代码从 CIImage 返回了 UIImage,而没有正确利用 CGContext 来返回 UIImage。这是解决问题的更正二维码功能。

func generateQRCode(from string: String) -> UIImage? {
    let data = string.data(using: String.Encoding.ascii)

    if let filter = CIFilter(name: "CIQRCodeGenerator") {
        filter.setValue(data, forKey: "inputMessage")

        let transform = CGAffineTransform(scaleX: 12, y: 12)

        if let output = filter.outputImage?.applying(transform) {
            let context = CIContext()
            let cgImage = context.createCGImage(output, from: output.extent)
            return UIImage(cgImage: cgImage!)
        }
    }

    return nil
}

【讨论】:

  • 如您所知,CIImage 是图像处理函数的集合,它没有具体的位图缓冲区。用这些东西创建的UIImage 可能会返回nil for cgImageCIImage.init(image:) 可能会返回nil。无论如何,干得好。你的代码和我准备的一模一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 2013-11-29
  • 2012-01-15
  • 1970-01-01
  • 2017-08-30
  • 1970-01-01
相关资源
最近更新 更多