首页 文章

将UIImage转换为CIImage返回nil

提问于
浏览
-1

我正在尝试将 UIImage 从imageView转换为 CIImage 以进行过滤 . 但是,我无法让 CIImage 拥有一个值 .

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

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

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

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

但也返回零 .

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

我需要将 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!)
}

运行此函数时,我在最后一行得到致命的解包nil错误 . 使用调试器,我发现ciInput是nil,它不应该是 .

编辑2:调用makeWhiteTransparent之前imageView上的图像是使用此函数生成的QR码:

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
}

1 回答

  • 2

    所以问题出在我的二维码生成中 . 代码从CIImage返回了一个UIImage而没有正确使用CGContext来返回UIImage . 以下是修正问题的修正QR码功能 .

    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
    }
    

相关问题