Created
May 21, 2023 21:34
-
-
Save rolandcrosby/2b4a4d7e494065dfd9b242dca292ed16 to your computer and use it in GitHub Desktop.
Swift QR code decoder
This file contains hidden or 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 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