iosswiftuiimagebarcode

How to get a quality barcode image from string in ios, swift


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!)

    }
}

so this generates a accurate image. but the quality is low. how can I increase the quality of the image.(I cant increase the size of the image, if I do so it looks liked blured)


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))
    }