0

I'm using the below code from this link to generate a Code128 barcode from a string. For some reason it's not woking. The function does returns an image but I'm not able to see it in the simulator after assigning the image to a UIImageView.

 class Barcode {

    class func fromString(string : String) -> UIImage? {

        let data = string.data(using: .ascii)
        let filter = CIFilter(name: "CICode128BarcodeGenerator")
        filter?.setValue(data, forKey: "inputMessage")

        return UIImage(ciImage: (filter?.outputImage)!)
    }

}

Have imported CoreImage. Function call:

let barcodeImg = Barcode.fromString(string: number)
self.userBarcodeImageView.image = barcodeImg

Can anyone tell me what the issue is?

Solved

Substituted the code for this function, found in this link

func generateBarcode(from string: String) -> UIImage? {

let data = string.data(using: String.Encoding.ascii)

if let filter = CIFilter(name: "CICode128BarcodeGenerator") {
    filter.setDefaults()
    //Margin
    filter.setValue(7.00, forKey: "inputQuietSpace")
    filter.setValue(data, forKey: "inputMessage")
    //Scaling
    let transform = CGAffineTransform(scaleX: 3, y: 3)

    if let output = filter.outputImage?.applying(transform) {
        let context:CIContext = CIContext.init(options: nil)
        let cgImage:CGImage = context.createCGImage(output, from: output.extent)!
        let rawImage:UIImage = UIImage.init(cgImage: cgImage)

        //Refinement code to allow conversion to NSData or share UIImage. Code here:
        //http://stackoverflow.com/questions/2240395/uiimage-created-from-cgimageref-fails-with-uiimagepngrepresentation
        let cgimage: CGImage = (rawImage.cgImage)!
        let cropZone = CGRect(x: 0, y: 0, width: Int(rawImage.size.width), height: Int(rawImage.size.height))
        let cWidth: size_t  = size_t(cropZone.size.width)
        let cHeight: size_t  = size_t(cropZone.size.height)
        let bitsPerComponent: size_t = cgimage.bitsPerComponent
        //THE OPERATIONS ORDER COULD BE FLIPPED, ALTHOUGH, IT DOESN'T AFFECT THE RESULT
        let bytesPerRow = (cgimage.bytesPerRow) / (cgimage.width  * cWidth)

        let context2: CGContext = CGContext(data: nil, width: cWidth, height: cHeight, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: cgimage.bitmapInfo.rawValue)!

        context2.draw(cgimage, in: cropZone)

        let result: CGImage  = context2.makeImage()!
        let finalImage = UIImage(cgImage: result)

        return finalImage

    }
}

return nil
}

Got it to work.

alpha47
  • 305
  • 3
  • 17

1 Answers1

0

I had faced same issue. After long research find below solution.

Please ensure your imageView height and width should be an Integer number. If imageView height and width is float number then it will not genrate barcode image.

Hitesh Surani
  • 12,733
  • 6
  • 54
  • 65