Reputation: 5480
I have an image:
As you can clearly see, the barcode doesn't fit in very well with the UI :/
I thought a potential fix for this, was to "green screen" out the black in the image, leaving on the white part of the barcode.
The barcode itself is generated on the fly.
func generateBarcode(from string: String) -> UIImage? {
let data = string.data(using: String.Encoding.ascii)
if let filter = CIFilter(name: "CICode128BarcodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 3, y: 3)
if let output = filter.outputImage?.applying(transform) {
let invertFiler = CIFilter(name: "CIColorInvert")!
invertFiler.setValue(output, forKey: kCIInputImageKey)
return UIImage(ciImage: (invertFiler.outputImage?.applying(transform))!) //TODO: Remove force unwrap
}
}
return nil
}
Now I've heard I can use a "CIColorCube" filter but haven't been able to work out to use it.
Is removing the black part possible? And, if so, would you be able to help me out?
Thanks
Upvotes: 1
Views: 1709
Reputation: 89192
There is a filter (CIMaskToAlpha
) for taking gray images and using the gray level as an alpha value. For black and white images, this makes black transparent and white opaque-white, which I think is what you want.
func generateBarcode(from string: String) -> UIImage? {
let data = string.data(using: String.Encoding.ascii)
if let filter = CIFilter(name: "CICode128BarcodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 3, y: 3)
if let outputBarcode = filter.outputImage?.applying(transform) {
let invertFilter = CIFilter(name: "CIColorInvert")!
invertFilter.setValue(outputBarcode, forKey: kCIInputImageKey)
if let outputInvert = invertFilter.outputImage?.applying(transform) {
let mask = CIFilter(name: "CIMaskToAlpha")!
mask.setValue(outputInvert, forKey: kCIInputImageKey)
return UIImage(ciImage: (mask.outputImage?.applying(transform))!) //TODO: Remove force unwrap
}
}
}
return nil
}
If you put the resulting image on a background that is blue, you will see just the white bars.
PS: When you say "green screen", what you mean (in imaging language) is the pixel is transparent. This is represented by the alpha component of the color (R, G, B, A). This filter sets each pixel to white, but uses the original color to set the alpha. White (which is 1.0) is a fully opaque alpha, and Black (which is 0.0) is fully transparent. If you had other gray levels, those pixels would be semi-transparent white.
Upvotes: 1