如何从ios,swift中的字符串中获取高质量的条形码图像

问题描述 投票:2回答:3

我正在使用下面的字符串生成条形码图像。

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

    }
}

这样就可以生成准确的图像。但质量很低。如何提高图像的质量。(我不能增加图像的大小,如果我这样做,它看起来像blured)

ios swift uiimage barcode
3个回答
2
投票

CIImage转换为UIImage时,它会使用由CIImage确定的固定大小,如果您随后尝试将此图像缩放,例如将其指定为UIImageView,那么您将获得与缩放相关联的典型像素化一个位图。

在将图像指定给UIImage之前转换图像

if let barImage = filter.outputImage {
    let transform = CGAffineTransformMakeScale(5.0, 5.0)
    let scaled = barImage.imageByApplyingTransform(transform)
    return(UIImage(CIImage: scaled))
}

2
投票

试试transform让它更大

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

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

0
投票

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
}
© www.soinside.com 2019 - 2024. All rights reserved.