如何生成EAN13条形码?

时间:2015-12-22 16:45:22

标签: ios swift barcode ean-13

我试图创建一个简单的EAN13图像来显示字符串中的条形码。

我尝试使用此代码,但它只能生成代码128。我可以用什么来生成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")

3 个答案:

答案 0 :(得分:2)

你可以尝试这个EAN13BarcodeGenerator

用法非常简单:

% package require fileutil
% ::fileutil::updateInPlace file.txt {string map {a 0}}
% ::fileutil::cat file.txt
0bc0bc0bc

答案 1 :(得分:0)

与EAN 13完美配合

  func generateBarcode(from string: String) -> UIImage? {
    let data = string.data(using: String.Encoding.ascii)

    if let filter = CIFilter(name: "CICode128BarcodeGenerator") {
      filter.setValue(data, forKey: "inputMessage")
      let transform = CGAffineTransform(scaleX: 15, y: 15)

      if let output = filter.outputImage?.transformed(by: transform) {
        return UIImage(ciImage: output)
      }
    }

    return nil
  }

用法:

barCodeImageView.image = generateBarcode(from: "1234567890123")

答案 2 :(得分:-1)

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
}