Skip to content

Instantly share code, notes, and snippets.

@rolandcrosby
Created May 21, 2023 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rolandcrosby/2b4a4d7e494065dfd9b242dca292ed16 to your computer and use it in GitHub Desktop.
Save rolandcrosby/2b4a4d7e494065dfd9b242dca292ed16 to your computer and use it in GitHub Desktop.
Swift QR code decoder
import Foundation
import CoreImage
let arguments = CommandLine.arguments
if arguments.count < 2 {
fatalError("Usage: \(arguments[0]) filename [filename...]")
}
let context = CIContext()
guard let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: context) else {
fatalError("Unable to initialize detector")
}
for filePath in arguments.dropFirst() {
let imageURL = URL(filePath: filePath)
guard let image = CIImage(contentsOf: imageURL) else {
fatalError("Unable to load image \(filePath)")
}
let features = detector.features(in: image)
print(filePath)
if features.count == 0 {
print("No QR codes detected")
continue
}
for feature in features {
let feature = feature as! CIQRCodeFeature
let descriptor = feature.symbolDescriptor!
let payload = descriptor.errorCorrectedPayload
if let message = feature.messageString {
print("Payload: \(message)")
} else {
print("Payload can't be interpreted as string")
}
print(payload.map { String(format: "%02hhx", $0) }.joined())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment