Swift – 使用Google Cloud Vision OCR 自動辨識身分證 (Alamofire/原生URLSession)

申請流程2wqeiwqheiowqheoihoqwe

1.Google Api Console

https://console.developers.google.com/

2.申請Cloud Vision API

3.複製金鑰

public let API_GOOGLE_OCR = "https://vision.googleapis.com/v1/images:annotate?key=yourKey" //Google OCR

Alamofire

public func sendPostJsonRequest(parameters:[String:Any]?,url:String,success:@escaping (JSON) -> Void,failure:@escaping (Error)-> Void,statusCode:@escaping (NSInteger) -> Void, isLoading: Bool = true) {
    if isLoading {
        loadingView.showLoading(nil)
    }
    Alamofire.request(URL(string: url)!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in
        switch response.result {
        case .success:
            success(JSON(response.result.value!))
        case .failure(let error):
            failure(error)
            statusCode(response.response?.statusCode ?? 400)
        }
        if isLoading {
            self.loadingView.hideLoading()
        }
    }
}

辨識 zh/en(中文/英文)

/**
 * 提交Google認證
 */
public class func apiGoogleOcr(base64ImageString:String,
                           success:@escaping (JSON) -> Void,
                           failure:@escaping (Error) -> Void,
                           statusCode:@escaping (NSInteger) -> Void) {
    let parameters = ["requests":["image":["content":base64ImageString],"features":[["type":"TEXT_DETECTION"]],"imageContext":["languageHints":["zh","en"]]]] as [String : Any]
    APIManager.shared.sendPostJsonRequest(parameters: parameters, url: API_GOOGLE_OCR, success: success, failure: failure, statusCode: statusCode)
}

UIImage to Date
Date to base64 String

/// Google OCR辨識
/// - Parameter image: 身分證圖片
func postGoogleOcr(image: UIImage){
    let testImageData: NSData = image.jpegData(compressionQuality: 0.5)! as NSData
    let base64 = testImageData.base64EncodedString(options: .endLineWithCarriageReturn)
    IdCardManager.apiGoogleOcr(base64ImageString: base64, success: { [self](response) in

    }, failure: {_ in}, statusCode: {_ in})
}

原生 http post

yourKey 記得更換你自己的憑證

let semaphore = DispatchSemaphore (value: 0)
let testImageData: NSData = UIImage.init(named: "test2")!.jpegData(compressionQuality: 0.5)! as NSData
let base64ImageString = testImageData.base64EncodedString(options: .endLineWithCarriageReturn)

let parameters = ["requests":["image":["content":base64ImageString],"features":[["type":"TEXT_DETECTION"]],"imageContext":["languageHints":["zh","en"]]]] as [String : Any]
let postData = try? JSONSerialization.data(withJSONObject: parameters)
var request = URLRequest(url: URL(string: "https://vision.googleapis.com/v1/images:annotate?key=yourKey")!,timeoutInterval: Double.infinity)
request.addValue("text/plain", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data else {
        print(String(describing: error))
        return
    }
    print(String(data: data, encoding: .utf8)!)
    semaphore.signal()
}

task.resume()
semaphore.wait()

檢測照片

執行結果


發佈留言