将 UIImage 转换为 CIImage 返回 nil [英] Converting UIImage to CIImage Returns nil
问题描述
我正在尝试将 UIImage
从 imageView 转换为 CIImage
以对其进行过滤.但是,我无法让 CIImage
具有值.
I'm trying to convert the UIImage
from an imageView into a CIImage
for the purpose of filtering it. However, I cannot get the CIImage
to have a value.
以最简单的形式,这就是我正在尝试的:
In the simplest form, here's what I am trying:
let ciInput = CIImage(image: imageView.image!)
但 ciInput 始终为零.我也试过
but the ciInput always is nil. I have also tried
let ciInput = CIImage(cgImage: imageView.image!.cgImage)
但也返回 nil.
(imageView.image
不是 nil,但是 imageView.image!.cgImage
和 imageView.image!.ciImage
都是 nil)
(imageView.image
is not nil, but imageView.image!.cgImage
and imageView.image!.ciImage
are both nil)
我需要将 UIImage
从 imageView
转换为有效的 CIImage
.感谢任何帮助,谢谢!
I need to convert the UIImage
from the imageView
into a valid CIImage
. Any help is appreciated, thanks!
这是完整的功能代码
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,它不应该是.
When running this function, I get a fatal unwrapping nil error on the last line. Using the debugger, I discovered that the ciInput is nil, which it should not be.
编辑 2:调用makeWhiteTransparent之前imageView上的图片就是用这个函数生成的二维码:
EDIT 2: The image on the imageView before calling makeWhiteTransparent is a QR code generated with this function:
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
}
推荐答案
所以问题出在我的二维码生成上.该代码从 CIImage 返回一个 UIImage,而没有正确利用 CGContext 返回 UIImage.这是解决问题的更正后的二维码功能.
So the problem was in my QR Code generation. The code returned a UIImage from a CIImage without properly utilizing CGContext to return the UIImage. Here is the corrected QR Code function that fixed the issue.
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
}
这篇关于将 UIImage 转换为 CIImage 返回 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!