# 使用baidu的ocr识别图片中的文字 date: 2019-12-28 20:53:49 ## 一、准备 1. 用百度账户登录百度云,申请文字识别API应用,会得到AppID 、API Key、Secret Key。 2. VS管理NuGet包,搜索`Baidu.AI`后添加。 3. 最开始加入 ```c# using Baidu.Aip.Ocr; using Newtonsoft.Json.Linq; ``` ## 二、使用方法 ```c# if(string.IsNullOrEmpty(filePath)) { MessageBox.Show("未指定图片文件", "注意", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string API_KEY = "your key"; string SECRET_KEY = "your key"; Ocr client = new Ocr(API_KEY, SECRET_KEY) { Timeout = 60000 // 修改超时时间 }; try { //调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获 byte[] image = File.ReadAllBytes(filePath); var result = client.GeneralBasic(image); var lines = from txt in result.Root["words_result"] select txt; StringBuilder sb = new StringBuilder(); foreach (var line in lines) { sb.AppendLine(line["words"].ToString()); } tbResult.Text = sb.ToString(); } catch { MessageBox.Show("执行文字识别出错~!\r\n检查是否未接入网络?\r\n其他原因联系作者解决。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } ```
鲁ICP备17027395号-1