首先你得注册一个账号,然后再认证,其实有一个《接入指南》的
http://ai.baidu.com/docs#/Begin/top
然后创建你想要的应用,记录appid, api_key, secret_key
再新建项目,并NgGet “baidu.ai”,安装
添加身份证识别的选项
代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp2_test_baidu_idcard_demo
{
public partial class Form1 : Form
{
// 设置APPID/AK/SK
string APP_ID = "114****11";
string API_KEY = "c2jmHjrt4xL*****mLhGs";
string SECRET_KEY = "57Z7HlxuYtymZbZEhLIjn*****9TC";
Baidu.Aip.Ocr.Ocr client = null;
public Form1()
{
InitializeComponent();
client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
}
private void button1_Click(object sender, EventArgs e)
{
var token = getAccessToken(API_KEY, SECRET_KEY);
IdcardDemo();
}
public String getAccessToken(string clientId, string clientSecret)
{
String authHost = "https://aip.baidubce.com/oauth/2.0/token";
HttpClient client2 = new HttpClient();
List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
HttpResponseMessage response = client2.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
String result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
return result;
}
public void IdcardDemo()
{
var image = File.ReadAllBytes(@"G:\我自己\身份证\2s.jpg");
var idCardSide = "back";
// 调用身份证识别,可能会抛出网络等异常,请使用try/catch捕获
var result = client.Idcard(image, idCardSide);
Console.WriteLine(result);
// 如果有可选参数
var options = new Dictionary<string, object>{
{"detect_direction", "true"},
{"detect_risk", "false"}
};
// 带参数调用身份证识别
result = client.Idcard(image, idCardSide, options);
Console.WriteLine(result);
}
}
}
识别成功: