1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
public static string OCR_Custom(Image image)
{// Image 是一个类,它是用于处理图像和图形的基本类之一。
byte[] result;
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Png);
result = memoryStream.ToArray();
}
// request
string url = "https://server.simpletex.cn/api/latex_ocr/v2";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data;boundary=---------------------------boundary";
request.Method = "POST";
request.Headers["token"] = "";
string boundary = "---------------------------boundary";
byte[] boundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
string formDataTemplate = "--{0}\r\nContent-Type:application/octet-stream\r\nContent-Disposition: form-data; name=\"file\"; filename=\"image.png\"\r\nContent-Type: image/png\r\n\r\n";
string formData = string.Format(formDataTemplate, boundary);
byte[] formDataBytes = Encoding.UTF8.GetBytes(formData);
// 设置请求体长度
request.ContentLength = formDataBytes.Length + result.Length + boundaryBytes.Length;
// 将请求体数据写入请求流中
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(formDataBytes, 0, formDataBytes.Length);
requestStream.Write(result, 0, result.Length);
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
}
// 发送请求并获取响应
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// 处理响应
string responseContent;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
// Console.WriteLine(responseContent);
}
response.Close();
var resultData = ((JObject)JsonConvert.DeserializeObject(responseContent));
var data = resultData["res"];
var region = data["latex"];
var text = "$" +region.ToString() + "$";
TxtFormat.Root jsonRoot=new TxtFormat.Root ();
jsonRoot.result=new List<TxtFormat.TextBlock>();
jsonRoot.isHasLocation=true;// 判断是否含有坐标返回
TxtFormat.TextBlock textBlock = new TxtFormat.TextBlock ();
textBlock.Text = text;//json 内的文本
textBlock.TopLeft = new Point (0,0);// 左上角坐标
textBlock.TopRight = new Point (0,0);// 右上角坐标
textBlock.BottomRight =new Point (0,0);// 右下角坐标
textBlock.BottomLeft =new Point (0,0);// 左下角坐标
jsonRoot.result.Add (textBlock);
// `SerializeObject(object value)`:将对象序列化为 **JSON 字符串**。
return JsonConvert.SerializeObject (jsonRoot);
}
|