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版的簡單使用,,,,