2

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)

Jobs
  • 259
  • 2
  • 6
  • 19
  • what do mean - the quality is low? As described http://stackoverflow.com/questions/28542240/how-to-generate-a-barcode-from-a-string-in-swift, you will get an image with vertical lines 1 pixel wide. If the image you get (at 32 pixels high) has lines 1 pixel wide, it's hard to see how you could get any crisper - Looks like your problem is in how you enlarge the image – Russell Mar 07 '17 at 09:16

3 Answers3

2

Try transform to make it bigger

    let transform = CGAffineTransform(scaleX: 3, y: 3)

    if let output = filter.outputImage?.applying(transform) {
        return UIImage(ciImage: output)
    }
Đào Minh Hạt
  • 1,744
  • 11
  • 19
2

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))
}
Paulw11
  • 95,291
  • 12
  • 135
  • 153
  • what is the maximum scale that we can use – Jobs Mar 07 '17 at 09:43
  • As far as I know, the only limit is the maximum value of a `CGFloat`. The transform is applied to the generation process, so quality isn't affected the way it is if you scale it after the image is a bitmap – Paulw11 Mar 07 '17 at 09:58
0

my two cents for OSX :)

func barCodeFromString(string : String) -> NSImage? {
    let data = string.data(using: .ascii)
    guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else{
        return nil
    }

    filter.setValue(data, forKey: "inputMessage")
    guard let ciImage : CIImage = filter.outputImage else{
        return nil
    }

    let transform = CGAffineTransform(scaleX: 5.0, y: 5.0)
    let scaled = ciImage.transformed(by: transform)

    let rep = NSCIImageRep(ciImage: scaled)
    let nsImage = NSImage(size: rep.size)
    nsImage.addRepresentation(rep)
    return nsImage
}
ingconti
  • 9,213
  • 2
  • 51
  • 39