Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
QR Code Generator written in Swift 4
import Quartz
extension CGImage {
class func qrCodeImage(from string: String, scale: CGFloat = 1) -> CGImage? {
let stringData = string.data(using: .utf8)
let transform = CGAffineTransform(scaleX: scale, y: scale)
guard let filter = CIFilter(name: "CIQRCodeGenerator") else {
return nil
}
filter.setValue(stringData, forKey: "inputMessage")
filter.setValue("H", forKey: "inputCorrectionLevel")
guard let ciImage = filter.outputImage?.transformed(by: transform) else {
return nil
}
let cgImage = CIContext().createCGImage(ciImage, from: ciImage.extent)
return cgImage
}
func data(type: CFString, dpi: CGFloat = 72) -> NSData? {
let prop: [CFString : Any] = [kCGImagePropertyIPTCImageType: 1.0,
kCGImagePropertyDPIWidth: dpi,
kCGImagePropertyDPIHeight: dpi]
let outputData = NSMutableData()
let destination = CGImageDestinationCreateWithData(outputData, type, 1, nil)!
CGImageDestinationAddImage(destination, self, prop as CFDictionary)
CGImageDestinationFinalize(destination)
return outputData
}
}
// QRコード連続並列生成
let scale: CGFloat = 5
let dpi: CGFloat = 144
let maxCount = 100
// 並列処理で一括生成
DispatchQueue.concurrentPerform(iterations: maxCount) { num in
autoreleasepool {
let numberString = String(format: "%04d", num)
if let pngData = CGImage.qrCodeImage(from: numberString, scale: scale)?.data(type: kUTTypePNG, dpi: dpi) {
pngData.write(toFile: "/tmp/\(numberString).png", atomically: true)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.