iosswiftuiimagebarcode

How to get a quality barcode image from string?


I'm generating an image with barcode using its string like below.

class BarCode {
    class func fromString(string : String) -> UIImage? {
        let data = string.dataUsingEncoding(NSASCIIStringEncoding)
        let filter = CIFilter(name: "CICode128BarcodeGenerator")
        filter!.setValue(data, forKey: "inputMessage")
        return UIImage(CIImage: filter!.outputImage!)
    }
}

This generates an accurate image, but the quality is low. How can I increase the quality of the image? I can't increase the size of the image. If I do so it looks blurred.


Solution

  • When the CIImage is converted to a UIImage it does so with a fixed size that is determined by the CIImage, if you subsequently try to scale this image up, say by assigning it to a UIImageView, then you will get the typical pixellation associated with scaling up a bitmap.

    Transform the image before assigning it to the UIImage

    if let barImage = filter.outputImage {
        let transform = CGAffineTransformMakeScale(5.0, 5.0)
        let scaled = barImage.imageByApplyingTransform(transform)
        return(UIImage(CIImage: scaled))
    }