Last active
December 21, 2023 10:32
-
-
Save doraTeX/20bf9d47bf026cd339c460334db8b013 to your computer and use it in GitHub Desktop.
QR Code Generator written in Swift 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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