I create one QRCode Generator with deferent color I want to remove the Gray color in Frame and have really one white color or clear color after I use the filter this gray color generate some time
let data = string.data(using: .isoLatin1, allowLossyConversion: false)
if let filter = CIFilter(name: "CIQRCodeGenerator") {
guard let colorFilter = CIFilter(name: "CIFalseColor") else { return nil }
filter.setValue(data, forKey: "inputMessage")
filter.setValue("H", forKey: "inputCorrectionLevel")
colorFilter.setValue(filter.outputImage, forKey: "inputImage")
colorFilter.setValue(CIColor(color: UIColor.clear), forKey: "inputColor1")
colorFilter.setValue(CIColor(color: UIColor.black), forKey: "inputColor0")
guard let qrCodeImage = colorFilter.outputImage
else {
return nil
}
let scaleX = imageView.frame.size.width / qrCodeImage.extent.size.width
let scaleY = imageView.frame.size.height / qrCodeImage.extent.size.height
let transform = CGAffineTransform(scaleX: scaleX, y: scaleY)
if let output = colorFilter.outputImage?.transformed(by: transform) {
let image = convert(cmage:(output.transformed(by: CGAffineTransform(scaleX: scaleX, y: scaleY))))
return image
}
}
return nil
}
func convert(cmage:CIImage) -> UIImage
{
let context:CIContext = CIContext.init(options: nil)
let cgImage:CGImage = context.createCGImage(cmage, from: cmage.extent)!
let image:UIImage = UIImage.init(cgImage: cgImage)
return image
}
if I don't use the filter for change the color I don't have this problem or If I used the blue color I have one frame with aqua blue color
Using the extension from the link I posted as a starting point:
extension String {
func qrCode(background: UIColor = .white, color: UIColor = .black, output: CGSize = CGSize(width: 250, height: 250))-> UIImage? {
guard
let data = data(using: .isoLatin1),
let filter = CIFilter(name: "CIQRCodeGenerator")
else { return nil }
filter.setValue(data, forKey: "inputMessage")
filter.setValue("M", forKey: "inputCorrectionLevel")
guard let image = filter.outputImage
else { return nil }
let size = image.extent.integral
let matrix = CGAffineTransform(scaleX: output.width / size.width, y: output.height / size.height)
UIGraphicsBeginImageContextWithOptions(output, false, 0)
defer { UIGraphicsEndImageContext() }
guard
let colorFilter = CIFilter(name: "CIFalseColor",
parameters: ["inputImage" : image.transformed(by: matrix),
"inputColor1": CIColor(color: background) ,
"inputColor0": CIColor(color: color)]),
let coloredImage = colorFilter.outputImage
else { return nil }
UIGraphicsBeginImageContextWithOptions(output, false, 0)
defer { UIGraphicsEndImageContext() }
UIImage(ciImage: coloredImage).draw(in: CGRect(origin: .zero, size: output))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
let link = "https://stackoverflow.com/questions/51178573/swift-image-data-from-ciimage-qr-code-how-to-render-cifilter-output?noredirect=1"
if let coloredQRCode = link.qrCode(color: .red, output: CGSize(width: 500, height: 500)) {
coloredQRCode
}