4

I'm trying to create a simple EAN13 image to show a barcode from a String.

I tried with this code but it can only generate a code128. What can I use to generate a EAN13?

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

let img = Barcode.fromString("1234567890123")
jcaron
  • 17,302
  • 6
  • 32
  • 46
Ivan Territo
  • 43
  • 2
  • 7
  • 1
    `CIFilter` doesn't appear to support EAN13, just QR Code, Aztec, Code 128, and PDF 417. – rmaddy Dec 22 '15 at 16:52
  • 4
    Possible duplicate of [Barcode Generation inside of IOS](http://stackoverflow.com/questions/5759073/barcode-generation-inside-of-ios) – jcaron Dec 22 '15 at 17:22

2 Answers2

2

you can try this EAN13BarcodeGenerator

Usage is pretty simple:

BarCodeView *barCodeView = [[BarCodeView alloc] initWithFrame:kBarCodeFrame];
[self.view addSubview:barCodeView];
[barCodeView setBarCode:GetNewRandomEAN13BarCode()];
ale_stro
  • 806
  • 10
  • 23
  • 1
    Swift version: let rect = CGRect(x: 100, y: 55, width: 113, height: 100) let barcodeView = BarCodeView(frame: rect) self.view.addSubview(barcodeView) barcodeView.barCode = "4012345678901" – Massimo Fazzolari Sep 19 '18 at 07:11
-5

my two cents for osx..

func barCodeFromString(string : String, destSize: NSSize) -> 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 c_size = ciImage.extent.size

    let w_ratio = destSize.width/c_size.width
    let h_ratio = destSize.height/c_size.height
    let ratio = w_ratio>h_ratio ? h_ratio : w_ratio
    let transform = CGAffineTransform(scaleX: ratio, y: ratio)
    let scaled = ciImage.transformed(by: transform)

    let rep = NSCIImageRep(ciImage: scaled)
    let nsImage = NSImage(size: rep.size)
    nsImage.addRepresentation(rep)
    return nsImage
}
ingconti
  • 10,876
  • 3
  • 61
  • 48