Notice
Recent Posts
Recent Comments
Link
투케이2K
655. (ios/swift5) IOS import Vision 사용해 QR 및 Barcode 이미지 파일 (png, jpg) 스캔 수행 본문
IOS
655. (ios/swift5) IOS import Vision 사용해 QR 및 Barcode 이미지 파일 (png, jpg) 스캔 수행
투케이2K 2026. 1. 1. 13:04728x90
[개발 환경 설정]
개발 툴 : XCODE
개발 언어 : SWIFT5

[소스 코드]
// --------------------------------------------------------------------------------------
[개발 및 테스트 환경]
// --------------------------------------------------------------------------------------
- 언어 : Swift5
- 개발 툴 : Xcode
- 기술 구분 : Vision / QR / Barcode
- 사전) VNDetectBarcodesRequest 간단 설명 및 사용 범위 :
>> Apple 공식 / 안정적
>> import Vision 만 하면 바로 사용 가능
>> QR 코드 디코딩 가능
>> 1D / 2D 바코드 디코딩 가능
>> 이미지 파일 디코딩 가능
- 사전) QR 및 바코드가 인식되지 않는 경우 정리 :
>> 이미지 가로 해상도 부족 (CODE 128은 600px 이상 권장)
>> 바코드 좌우 여백 부족
>> PNG 투명 배경
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
[소스 코드]
// --------------------------------------------------------------------------------------
// -------------------------------------------------------------------
// MARK: [QR 및 Barcode 저장 된 이미지 스캔 메소드]
// -------------------------------------------------------------------
// [필요 import]
// -------------------------------------------------------------------
// import AVKit
// import Vision
// -------------------------------------------------------------------
// [호출 방법]
// -------------------------------------------------------------------
/*
if let file = Bundle.main.path(forResource: "testQrImg", ofType: "png") {
S_Log._W_(description: "File Found", data: nil)
let image = UIImage(contentsOfFile: file)
self.getQrBarcodeImageFileScan(image: image){(result) in
S_Log._F_(description: "QR 및 바코드 스캔 콜백 결과 확인", data: ["\(result)"])
}
}
else {
S_Log._E_(description: "File Not Found", data: nil)
}
*/
// -------------------------------------------------------------------
// [참고 사항]
// -------------------------------------------------------------------
// 👉 VNDetectBarcodesRequest의 일부 바코드/QR 인식은 iOS 시뮬레이터에서 정상 동작하지 않을 수 있습니다.
// 특히 iOS 17 시뮬레이터에서는 Quagga / Espresso(CoreML) 모델 로딩 실패 로그가 발생하고 결과가 “바코드 없음”으로 떨어지는 경우가 많습니다.
// -------------------------------------------------------------------
func getQrBarcodeImageFileScan(image: UIImage?, completion: @escaping (String)->()) {
DispatchQueue.main.async {
S_Log._D_(description: "QR 및 Barcode 저장 된 이미지 스캔 수행", data: nil)
var returnData = ""
if image != nil {
// ✅ png 파일인 경우 투명 알파 제거
let renderer = UIGraphicsImageRenderer(size: image!.size)
let img = renderer.image { _ in
UIColor.white.setFill()
UIRectFill(CGRect(origin: .zero, size: image!.size))
image!.draw(at: .zero)
}
// cgImage 변경 수행
guard let cgImage = img.cgImage
else {
S_Log._E_(description: "QR 및 Barcode 저장 된 이미지 스캔 에러 발생", data: ["[Error] : CGImage 변환 실패"])
completion("")
return
}
// VNDetectBarcodesRequest 객체 생성
let request = VNDetectBarcodesRequest { request, error in
if let error = error {
S_Log._E_(description: "QR 및 Barcode 저장 된 이미지 스캔 에러 발생", data: ["[Error] : Vision - " + error.localizedDescription])
completion("")
return
}
guard let results = request.results as? [VNBarcodeObservation], !results.isEmpty
else {
S_Log._E_(description: "QR 및 Barcode 저장 된 이미지 스캔 에러 발생", data: ["[Error] : Vision - Result Not Found"])
completion("")
return
}
for barcode in results {
print("Qr 및 Barcode 스캔 : Vision - 심볼 : ", barcode.symbology.rawValue)
print("Qr 및 Barcode 스캔 : Vision - 값 : ", barcode.payloadStringValue ?? "nil")
returnData = barcode.payloadStringValue ?? "" // ✅ 리턴 변수에 삽입
}
if returnData != "" {
S_Log._W_(description: "QR 및 Barcode 저장 된 이미지 스캔 성공", data: ["[returnData] : " + returnData])
completion(returnData)
}
else {
S_Log._E_(description: "QR 및 Barcode 저장 된 이미지 스캔 에러 발생", data: ["[Error] : Vision - Search Data Not Found"])
completion("")
}
}
// 🔑 QR + Barcode 동시 허용
request.symbologies = [
.QR,
.EAN13,
.EAN8,
.UPCE,
.Code128,
.Code39,
.Code93,
.PDF417,
.DataMatrix,
.Aztec
]
// 안정성 옵션 (선택)
//request.usesCPUOnly = true
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
do {
try handler.perform([request])
} catch {
S_Log._E_(description: "QR 및 Barcode 저장 된 이미지 스캔 에러 발생", data: ["[Exception] : Vision - " + error.localizedDescription])
completion("")
}
}
else {
S_Log._E_(description: "QR 및 Barcode 저장 된 이미지 스캔 에러 발생", data: ["[Error] : UIImage Is Nil"])
completion("")
}
}
}
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
[참고 사이트]
// --------------------------------------------------------------------------------------
[라이브러리] [Ios] QRCodeReader (Swift / Camera / QR)
https://blog.naver.com/kkh0977/222915053266?trackingCode=blog_bloghome_searchlist
[라이브러리] [Ios] QRCode (Swift / Camera / QR)
https://blog.naver.com/kkh0977/222915071986?trackingCode=blog_bloghome_searchlist
[Mobile] 모바일 ( android , ios ) 에서 QR 코드 생성 시 화면 밝기 및 QR 코드 사이즈 최대 표시 Alert 팝업창 활성
https://blog.naver.com/kkh0977/223624876714?trackingCode=blog_bloghome_searchlist
[Mobile] 모바일 ( android , ios ) 에서 QR 코드 스캔 후 정보 확인 및 다시 스캔 로직 수행
https://blog.naver.com/kkh0977/223624907452?trackingCode=blog_bloghome_searchlist
// --------------------------------------------------------------------------------------
728x90
반응형
'IOS' 카테고리의 다른 글
Comments
