当前位置:网站首页>C# asp. Net calling Baidu character recognition interface
C# asp. Net calling Baidu character recognition interface
2022-04-21 07:50:00 【Gentleness901】
Baidu character recognition interface
public class BaiduHelper
{
private static readonly string clientId = ""; //" Baidu cloud application AK";
private static readonly string clientSecret = ""; //" Baidu cloud application SK";
/// <summary>
/// Image recognition
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static string Ocr(string filePath)
{
try
{
//string img = HttpUtility.UrlEncode(GetBase64FromImage(filePath));
string img = HttpUtility.UrlEncode(ImageToBase64(filePath));
//string token = GetAccessToken();
//token = new Regex(
// "\"access_token\":\"(?<token>[^\"]*?)\"",
// RegexOptions.CultureInvariant
// | RegexOptions.Compiled
// ).Match(token).Groups["token"].Value.Trim();
//var url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
string url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=";//?
var list = new List<KeyValuePair<string, string>>
{
//new KeyValuePair<string, string>("access_token", token),
new KeyValuePair<string, string>("image", img),
new KeyValuePair<string, string>("language_type", "CHN_ENG")
};
var data = new List<string>();
foreach (var pair in list)
data.Add(pair.Key + "=" + pair.Value);
string json = HttpPost(url, string.Join("&", data.ToArray()));
//var regex = new Regex(
// "\"words_result\": \"(?<words>[\\s\\S]*?)\"",
// RegexOptions.CultureInvariant
// | RegexOptions.Compiled
// );
//var str = new StringBuilder();
//foreach (Match match in regex.Matches(json))
//{
// str.AppendLine(match.Groups["words"].Value.Trim());
//}
return json.ToString();
}
catch (Exception ex)
{
return ex.Message;
}
}
public static string GetBase64FromImage(string imagefile)
{
string base64String;
try
{
byte[] arr;
using (var bmp = new Bitmap(imagefile))
{
using (var ms = new MemoryStream())
{
bmp.Save(ms, ImageFormat.Jpeg);
arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
}
}
base64String = Convert.ToBase64String(arr);
}
catch (Exception ex)
{
throw new Exception("Something wrong during convert!");
}
return base64String;
}
/**
* Network picture conversion Base64 Methods
*
* @param netImagePath
*/
private static string ImageToBase64(string fileFullName)
{
try
{
Image img = UrlToImage(fileFullName);
Bitmap bmp = new Bitmap(img);
MemoryStream ms = new MemoryStream();
var suffix = fileFullName.Substring(fileFullName.LastIndexOf('.') + 1,
fileFullName.Length - fileFullName.LastIndexOf('.') - 1).ToLower();
var suffixName = suffix == "png"
? ImageFormat.Png
: suffix == "jpg" || suffix == "jpeg"
? ImageFormat.Jpeg
: suffix == "bmp"
? ImageFormat.Bmp
: suffix == "gif"
? ImageFormat.Gif
: ImageFormat.Jpeg;
bmp.Save(ms, suffixName);
byte[] arr = new byte[ms.Length]; ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length); ms.Close();
string base64Str = Convert.ToBase64String(arr);
return PrefectBase64(base64Str);
}
catch (Exception ex)
{
return null;
}
}
public static Image UrlToImage(string url)
{
WebClient mywebclient = new WebClient();
byte[] Bytes = mywebclient.DownloadData(url);
using (MemoryStream ms = new MemoryStream(Bytes))
{
Image outputImg = Image.FromStream(ms);
return outputImg;
}
}
private static string PrefectBase64(string Base64Str)
{
string dummyData = Base64Str.Replace("%", "").Replace(",", "").Replace(" ", "+");
if (dummyData.Length % 4 > 0)
{
dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
}
return dummyData;
}
public static string GetAccessToken()
{
string url = "https://aip.baidubce.com/oauth/2.0/token";
var list = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret)
};
var data = new List<string>();
foreach (var pair in list)
data.Add(pair.Key + "=" + pair.Value);
return HttpGet(url, string.Join("&", data.ToArray()));
}
public static string HttpGet(string url, string data)
{
var request = (HttpWebRequest)WebRequest.Create(url + (data == "" ? "" : "?") + data);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
using (var response = (HttpWebResponse)request.GetResponse())
{
Stream stream = response.GetResponseStream();
string s = null;
if (stream != null)
{
using (var reader = new StreamReader(stream, Encoding.GetEncoding("utf-8")))
{
s = reader.ReadToEnd();
reader.Close();
}
stream.Close();
}
return s;
}
}
public static string HttpPost(string url, string data)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = Encoding.UTF8.GetByteCount(data);
Stream stream = request.GetRequestStream();
var writer = new StreamWriter(stream, Encoding.GetEncoding("gb2312"));
writer.Write(data);
writer.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
Stream res = response.GetResponseStream();
if (res != null)
{
var reader = new StreamReader(res, Encoding.GetEncoding("utf-8"));
string retString = reader.ReadToEnd();
reader.Close();
res.Close();
return retString;
}
}
return "";
}
}
版权声明
本文为[Gentleness901]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210629483727.html
边栏推荐
猜你喜欢
随机推荐
laravel实现打包多个文件,并下载
音乐 下载 等文件名都变成了相同的名字的解决方法
Exit and Status
leetcode 19. Delete the penultimate node of the linked list
ETL之Kettle工具十大功能特性详解
Usage notes of Axure product prototype tool
You cannot set a form field before rendering a field associated with the value
STM32系统和自定义bootloader的实现和应用
Postgre(pg)-SQL脚本记录
php 输出两个指定日期中间的所有时间
Axure产品原型工具使用笔记
服务器基本的安全防护设置
Use case diagram of umlet instructions
pycharm 最新导入PIL库的方法
C# WebService 接口 通过Request请求获取json参数
关于数据治理平台中数据仓库ODS、DW和DM概念理解
批处理解析域名的ip地址并打开网页
Creating Oracle database in Navicat tool
Assembly language -- Method of memory location
《Qt 5.12实战》简介





![[question 31] create two identical pets](/img/3a/de5321bddd8fb24765a532a88d6809.png)



