Instantly share code, notes, and snippets.

Embed
What would you like to do?
QR Code Generator written in Swift 4
import Cocoa
extension NSBitmapImageRep {
func representation(type: CFString, dpi: CGFloat) -> 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.cgImage!, prop as CFDictionary)
CGImageDestinationFinalize(destination)
return outputData
}
}
extension NSImage {
class func qrCodeImage(from string: String, scale: CGFloat = 1) -> NSImage? {
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")
guard let ciImage = filter.outputImage?.transformed(by: transform) else {
return nil
}
let ciImageRep = NSCIImageRep(ciImage: ciImage)
let nsImage = NSImage(size: ciImageRep.size)
nsImage.addRepresentation(ciImageRep)
return nsImage
}
func pngData(dpi: CGFloat = 72) -> NSData? {
guard let tiffData = self.tiffRepresentation,
let bitmapImageRep = NSBitmapImageRep(data: tiffData) else {
return nil
}
return bitmapImageRep.representation(type: kUTTypePNG, dpi: dpi)
}
}
// QRコード連続並列生成
let scale: CGFloat = 1
let dpi: CGFloat = 72
let maxCount = 1000
// 並列処理で一括生成
DispatchQueue.concurrentPerform(iterations: maxCount) { num in
autoreleasepool {
let numberString = String(format: "%04d", num)
if let pngData = NSImage.qrCodeImage(from: numberString, scale: scale)?.pngData(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