我正在使用下面的字符串生成条形码图像。
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)
当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))
}
试试transform
让它更大
let transform = CGAffineTransform(scaleX: 3, y: 3)
if let output = filter.outputImage?.applying(transform) {
return UIImage(ciImage: output)
}
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
}