如何在Swift中从字符串生成条形码?

rqmkfv5c  于 12个月前  发布在  Swift
关注(0)|答案(5)|浏览(99)

我是一个新的iOS开发者。我想知道如何在Swift中生成条形码。
我已经有了代码,有多个资源可以学习如何读取条形码,但我没有找到任何关于从字符串生成条形码的内容。
多谢了!
P.S.我知道有一个类似的问题,但这是针对Obj-C的。我不知道Obj-C,我发现很难从. NET中走出来。

3lxsmp7m

3lxsmp7m1#

您可以使用CoreImage(import CoreImage)过滤器来完成此操作!

class Barcode {
        class func fromString(string : String) -> UIImage? {
             let data = string.data(using: .ascii)
             if let filter = CIFilter(name: "CICode128BarcodeGenerator") {
                  filter.setValue(data, forKey: "inputMessage")
                  if let outputCIImage = filter.outputImage {
                       return UIImage(ciImage: outputCIImage)
                  }
             }
             return nil
        }
    }

    let img = Barcode.fromString("whateva")

字符串
一个新的版本,带有guard和可失败的初始化程序:

extension UIImage {

    convenience init?(barcode: String) {
        let data = barcode.data(using: .ascii)
        guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else {
            return nil
        }
        filter.setValue(data, forKey: "inputMessage")
        guard let ciImage = filter.outputImage else {
            return nil
        }
        self.init(ciImage: ciImage)
    }

}


使用方法:

let barcode = UIImage(barcode: "some text") // yields UIImage?


根据文档:
根据ISO/IEC 15417:2007标准生成表示输入数据的输出图像。输出图像中条形码的每个模块(垂直线)的宽度为1像素。条形码的高度为32像素。要从字符串或URL创建条形码,请使用NSASCIIStringEncoding字符串编码将其转换为NSData对象。

y1aodyip

y1aodyip2#

改进代码:

  • 条码缩放
  • 设置条形码图像边距
  • 将UIImage转换为NSData(由于某些原因,上面的代码无法实现)。
  • 它不会在共享条形码图像时失败(可能是因为同一个bug)
  • 斯威夫特3号酒店,纽约**
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
}

字符串

vvppvyoh

vvppvyoh3#

如果你的部署目标至少是iOS 8,你可以使用Core Image。下面是我的BarcodeGenerator类(你需要import CoreImage):

class BarcodeGenerator {
    enum Descriptor: String {
        case code128 = "CICode128BarcodeGenerator"
        case pdf417 = "CIPDF417BarcodeGenerator"
        case aztec = "CIAztecCodeGenerator"
        case qr = "CIQRCodeGenerator"
    }

    class func generate(from string: String, 
                         descriptor: Descriptor, 
                               size: CGSize) -> CIImage? {
        let filterName = descriptor.rawValue

        guard let data = string.data(using: .ascii),
            let filter = CIFilter(name: filterName) else {
                return nil
        }

        filter.setValue(data, forKey: "inputMessage")

        guard let image = filter.outputImage else {
            return nil
        }

        let imageSize = image.extent.size

        let transform = CGAffineTransform(scaleX: size.width / imageSize.width,
                                               y: size.height / imageSize.height)
        let scaledImage = image.transformed(by: transform)

        return scaledImage
    }
}

字符串
可以这样用

BarcodeGenerator.generate(from: "barcode-string", 
                     descriptor: .code128, 
                          size: CGSize(width: 800, height: 300))

h9a6wy2h

h9a6wy2h4#

像这样使用,

func createBarcodeFromString(barcode:String)->UIImage?{

    let data = self.data(using: .isoLatin1)
    guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else {
        return nil
    }
    filter.setValue(data, forKey: "inputMessage")
    filter.setValue(7.0, forKey:"inputQuietSpace")
    guard var ciImage = filter.outputImage else {
        return nil
    }

    let imageSize = ciImage.extent.integral
    let outputSize = CGSize(width:320, height: 60)
    ciImage = ciImage.transformed(by:CGAffineTransform(scaleX: outputSize.width/imageSize.width, y: outputSize.height/imageSize.height))

    let image = convertCIImageToUIImage(ciimage: ciImage)
    return image
}

func convertCIImageToUIImage(ciimage:CIImage)->UIImage{
    let context:CIContext = CIContext.init(options: nil)
    let cgImage:CGImage = context.createCGImage(ciimage, from: ciimage.extent)!
    let image:UIImage = UIImage.init(cgImage: cgImage)
    return image
}

字符串

dly7yett

dly7yett5#

answer from Matteo Pacini类似,这里是使用较新的类型安全CIFilter示例(iOS 13.0+)的版本。

import UIKit
import CoreImage.CIFilterBuiltins // Type-safe CIFilter instances, iOS 13.0+

extension UIImage {
    static func barcode(
        string: String,
        height: Float,
        quietSpace: Float
    ) -> UIImage? {
        guard let message = string.data(using: String.Encoding.ascii) else {
            return nil
        }
        let filter = CIFilter.code128BarcodeGenerator()
        filter.message = message
        filter.barcodeHeight = height
        filter.quietSpace = quietSpace
        guard let outputImage = filter.outputImage else {
            return nil
        }
        return UIImage(ciImage: outputImage)
    }
}

字符串
使用方法:

imageView.image = .barcode(
    string: "0123456789",
    height: 64,
    quietSpace: 10
)


相关文件:

相关问题