MVC就不说了,新建一个MVC程序。
然后在HomeController中,新增一个ActionResult BaiduAITest()
using Baidu.Aip.Ocr;
using Newtonsoft.Json.Linq;
using System.Web.Mvc;
namespace BaiDuAITest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult BaiduAITest()
{
string strPath = @"D:\guoshihao\Desktop\456.png";//需要识别的图片路径
string content = string.Empty;//图片内容
string apiKey = "Ov4****************3Yk";
string secretKey = "wW***********************vBa";
Ocr client = new Ocr(apiKey, secretKey)
{
Timeout = 30000//延时时间
};
byte[] image =System.IO.File.ReadAllBytes(strPath);//需要识别的图片路径
//JObject result = client.GeneralBasic(image);//json数据,具体格式可以看官方API说明
var result = client.AccurateBasic(image);
JObject o = JObject.Parse(result.ToString());
int num = (int)o.SelectToken("words_result_num");
for (int i = 0; i < num; i++)
{
content += (string)o.SelectToken($"words_result[{i}].words");
}
ViewBag.Message = $"这就是图片中的文字:\r\n{content}";
return View();
}
}
}
然后在新增一个视图
测试图片:
运行结果:
这就是mvc版的简单使用,,,,