using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text; namespace Common.Utils
{
public static class OCRUtil
{
private const String Host = "https://ocrapi-document.taobao.com";
private const String Path = "/ocrservice/document";
private const String Method = "POST";
private const String Appcode = "************";
private static readonly IList<string> ImageExList = new List<string>()
{
".jpg",
".png",
".bmp"
}; /// <summary>
/// 确保图片可用
/// </summary>
/// <param name="fileName"></param>
private static void EnsureImageCanUse(string fileName)
{
if (string.IsNullOrWhiteSpace(fileName))
{
throw new ArgumentNullException(nameof(fileName), "文件名为空");
}
if (!File.Exists(fileName))
{
throw new FileNotFoundException("文件不存在", fileName);
}
string ex = System.IO.Path.GetExtension(fileName);
if (ImageExList.IndexOf(ex.ToLower()) == -)
{
throw new FileFormatException("图片格式需为jpg,png,bmp");
}
FileInfo fileInfo = new FileInfo(fileName);
if (fileInfo.Length > * * )
{
throw new Exception("文件不能大于4M");
}
} /// <summary>
/// 将图片转换为Base64字符串
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private static string ImageToBase64String(string fileName)
{
Bitmap bitmap = new Bitmap(fileName);
string ex = System.IO.Path.GetExtension(fileName).ToLower();
using (MemoryStream ms = new MemoryStream())
{
ImageFormat format;
switch (ex)
{
case ".png":
format = ImageFormat.Png;
break;
case ".jpg":
format = ImageFormat.Jpeg;
break;
default:
format = ImageFormat.Bmp;
break;
}
bitmap.Save(ms, format);
byte[] arr = new byte[ms.Length];
ms.Position = ;
ms.Read(arr, , (int)ms.Length);
ms.Close();
return Convert.ToBase64String(arr);
}
} /// <summary>
/// 阿里云OCR图片转文字
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string ImageToText(string fileName)
{
EnsureImageCanUse(fileName); String querys = "";
String bodys = "{\"img\":\"" + ImageToBase64String(fileName) + "\",\"url\":\"\",\"prob\":false}";
String url = Host + Path;
HttpWebRequest httpRequest = null;
HttpWebResponse httpResponse = null; if ( < querys.Length)
{
url = url + "?" + querys;
} if (Host.Contains("https://"))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
}
else
{
httpRequest = (HttpWebRequest)WebRequest.Create(url);
}
httpRequest.Method = Method;
httpRequest.Headers.Add("Authorization", "APPCODE " + Appcode);
//根据API的要求,定义相对应的Content-Type
httpRequest.ContentType = "application/json; charset=UTF-8";
if ( < bodys.Length)
{
byte[] data = Encoding.UTF8.GetBytes(bodys);
using (Stream stream = httpRequest.GetRequestStream())
{
stream.Write(data, , data.Length);
}
} httpResponse = (HttpWebResponse)httpRequest.GetResponse();
if (httpResponse.StatusCode != HttpStatusCode.OK)
{
throw new WebException("阿里云OCR接口调用识别失败");
} Stream st = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
string responseStr = reader.ReadToEnd(); OcrResult ocrResult = JsonConvert.DeserializeObject<OcrResult>(responseStr);
return OcrResultToString(ocrResult);
} private static string OcrResultToString(OcrResult ocrResult)
{
StringBuilder sb = new StringBuilder();
var wordList = ocrResult.prism_wordsInfo;
foreach (var item in wordList)
{
int leftX = item.pos[].x;
int blankSpaceCount = (int)Math.Floor((double)leftX / );
if (blankSpaceCount > )
{
sb.Append(' ', blankSpaceCount*);
}
sb.AppendLine(item.word);
}
return sb.ToString();
} public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
} /// <summary>
/// OCR识别结果
/// </summary>
public class OcrResult
{
public string sid { get; set; }
public string prism_version { get; set; }
public int prism_wnum { get; set; }
public List<Prism_Wordsinfo> prism_wordsInfo { get; set; }
public int height { get; set; }
public int width { get; set; }
public int orgHeight { get; set; }
public int orgWidth { get; set; }
} public class Prism_Wordsinfo
{
public string word { get; set; }
public IList<Pos> pos { get; set; }
} public class Pos
{
public int x { get; set; }
public int y { get; set; }
} }

阿里云OCR图片转换成文字识别调用的更多相关文章

  1. 利用百度AI OCR图片识别,Java实现PDF中的图片转换成文字

    序言:我们在读一些PDF版书籍的时候,如果PDF中不是图片,做起读书笔记的还好:如果PDF中的是图片的话,根本无法编辑,做起笔记来,还是很痛苦的.我是遇到过了.我们搞技术的,当然得自己学着解决现在的痛 ...

  2. 使用阿里云的图片识别成表格ocr(将图片表格转换成excel)

    为了简便财务总是要对照着别人发来的表格图片制作成自己的表格 图片识别 识别成表格 表格识别 ocr 使用阿里云api 购买(印刷文字识别-表格识别) https://market.aliyun.com ...

  3. ABBYY如何把图片转换成pdf格式

    在制作工作文件的时候,有时候会遇到需要进行文件格式转换的情况,比较常见的文件格式转换就包含了Office与pdf格式之间的转换.但除此之外,图片与pdf格式也是可以进行转换的,那么图片要怎么操作,才能 ...

  4. 教你一招:Word中的文字转换成表格,把表格转换成文字

    在使用office软件时,常常会在Word中加入表格,这时候我们一般想到的是,建立表格,然后一格一格的填写;或者用Excel表格制作在复制到Word文档中.其实在Word中就可以将文本文档转换成电子表 ...

  5. UI进阶 科大讯飞(1) 语音听写(语音转换成文字)

    一.科大讯飞开放平台: http://www.xfyun.cn/ 注册.登录之后创建新应用. 因为本项目只实现了语音听写,所以在SDK下载中心勾选语音听写单项SDK就可以了 开发平台选择iOS,应用选 ...

  6. jpg、png格式的图片转换成webp后颜色失真的问题

    今天简单的试用了一下 cweb.exe 将 jpg, png 格式的图片转换成 webp 格式. 我今天下载的是当前最新版:1.0.0 cwebp 3.jpg  -q 85 -o 3.webp 发现图 ...

  7. 使用CSS将图片转换成黑白(灰色、置灰)z转

    小tip: 使用CSS将图片转换成黑白(灰色.置灰) by zhangxinxu from http://www.zhangxinxu.com 本文地址:http://www.zhangxinxu.c ...

  8. [转]C#将image中的显示的图片转换成二进制

    本文转自:http://www.cnblogs.com/shuang121/archive/2012/07/09/2582654.html .将Image图像文件存入到数据库中 我们知道数据库里的Im ...

  9. 小tip: 使用CSS将图片转换成模糊(毛玻璃)效果

    去年盛夏之时,曾写过“小tip: 使用CSS将图片转换成黑白”一文,本文的模式以及内容其实走得是类似路线.CSS3 → SVG → IE filter → canvas. 前段时间,iOS7不是瓜未熟 ...

随机推荐

  1. 把时间留给重要的事——Markdown 模板功能上线

    你是否遇到过因为同事在任务中过于放飞自我而感到头疼?或者经历过因为内容描写的不系统而导致关键信息被忽视? 现在,CODING Markdown 模板功能将帮助你解决这些困扰. 功能介绍 CODING ...

  2. 从Windows转向Linux(在Windows下建立Deepin、Windows10双系统)

    我是19年3月转向使用Linux进行开发,没啥特别的理由,就是觉得使用Linux系统是每个程序员必须经历的吧. 选择版本 一开始,在网上了解到现在流行的Linux发行版有基于Redhat的,还有基于d ...

  3. qt+vs2017环境下XIMEA相机库的配置

    从第一篇博客出来之后就没再更新过博客,这一次再更新博客的时候已经是换了项目了,现在在搞双目视觉方面.刚开始接触这一方面,前几天一直在研究相机原本的库函数的调用问题 网上这一方面的很少,而且很多都是在u ...

  4. Error:"MetaStoreClient lost connection. Attempting to reconnect (1 of 24) after 5s. getCurrentNotificationEventId" occurs as HiveServer2 fails to start as it cannot connect to Metastore in HDP 3.0

    SupportKB Problem Description:After upgrading to HDP 3.0, the HiveServer2 fails to start and the fol ...

  5. Fusion Log

    What is Fusion Log? Also known as the Fusion Log or Assembly Binding Log Viewer. This tool is instal ...

  6. js生成[n,m]的随机数,js如何生成随机数,javascript随机数Math.random()

    一.预备知识 Math.ceil();  //向上取整. Math.floor();  //向下取整. Math.round();  //四舍五入. Math.random();  //0.0 ~ 1 ...

  7. CSS Modules In Webpack

    1)从形式上看,CSS Modules 是将CSS中的选择器转换为变量,然后在DOM中引用变量来引入样式. 2)从效果上看,CSS Modules 可以将CSS选择器名字转成随机字符串,保证选择器同名 ...

  8. pandas对Excel文件的读写操作

    1.将Excel数据读为dataframe 1.1 直接读取 df = pd.read_excel('data.xlsx') 1.2 根据sheet索引 xls = pd.ExcelFile('dat ...

  9. cAdvisor+Prometheus+Grafana监控docker

    cAdvisor+Prometheus+Grafana监控docker 一.cAdvisor(需要监控的主机都要安装) 官方地址:https://github.com/google/cadvisor ...

  10. 如何在ASP.NET Core中使用JSON Patch

    原文: JSON Patch With ASP.NET Core 作者:.NET Core Tutorials 译文:如何在ASP.NET Core中使用JSON Patch 地址:https://w ...