阿里云OCR图片转换成文字识别调用
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图片转换成文字识别调用的更多相关文章
- 利用百度AI OCR图片识别,Java实现PDF中的图片转换成文字
序言:我们在读一些PDF版书籍的时候,如果PDF中不是图片,做起读书笔记的还好:如果PDF中的是图片的话,根本无法编辑,做起笔记来,还是很痛苦的.我是遇到过了.我们搞技术的,当然得自己学着解决现在的痛 ...
- 使用阿里云的图片识别成表格ocr(将图片表格转换成excel)
为了简便财务总是要对照着别人发来的表格图片制作成自己的表格 图片识别 识别成表格 表格识别 ocr 使用阿里云api 购买(印刷文字识别-表格识别) https://market.aliyun.com ...
- ABBYY如何把图片转换成pdf格式
在制作工作文件的时候,有时候会遇到需要进行文件格式转换的情况,比较常见的文件格式转换就包含了Office与pdf格式之间的转换.但除此之外,图片与pdf格式也是可以进行转换的,那么图片要怎么操作,才能 ...
- 教你一招:Word中的文字转换成表格,把表格转换成文字
在使用office软件时,常常会在Word中加入表格,这时候我们一般想到的是,建立表格,然后一格一格的填写;或者用Excel表格制作在复制到Word文档中.其实在Word中就可以将文本文档转换成电子表 ...
- UI进阶 科大讯飞(1) 语音听写(语音转换成文字)
一.科大讯飞开放平台: http://www.xfyun.cn/ 注册.登录之后创建新应用. 因为本项目只实现了语音听写,所以在SDK下载中心勾选语音听写单项SDK就可以了 开发平台选择iOS,应用选 ...
- jpg、png格式的图片转换成webp后颜色失真的问题
今天简单的试用了一下 cweb.exe 将 jpg, png 格式的图片转换成 webp 格式. 我今天下载的是当前最新版:1.0.0 cwebp 3.jpg -q 85 -o 3.webp 发现图 ...
- 使用CSS将图片转换成黑白(灰色、置灰)z转
小tip: 使用CSS将图片转换成黑白(灰色.置灰) by zhangxinxu from http://www.zhangxinxu.com 本文地址:http://www.zhangxinxu.c ...
- [转]C#将image中的显示的图片转换成二进制
本文转自:http://www.cnblogs.com/shuang121/archive/2012/07/09/2582654.html .将Image图像文件存入到数据库中 我们知道数据库里的Im ...
- 小tip: 使用CSS将图片转换成模糊(毛玻璃)效果
去年盛夏之时,曾写过“小tip: 使用CSS将图片转换成黑白”一文,本文的模式以及内容其实走得是类似路线.CSS3 → SVG → IE filter → canvas. 前段时间,iOS7不是瓜未熟 ...
随机推荐
- Android values资源的定义
Android values资源是Xml格式的文件 上图定义了颜色(colors)字符串(strings)样式(style)三个资源文件 xml文件写在resources标签里 <?xml ve ...
- github常见操作和常见错误!错误提示:fatal: remote origin already exist
如果输入$ git remote add origin git@github.com:djqiang(github帐号名)/gitdemo(项目名).git 提示出错信息:fatal: remote ...
- 再谈AbstractQueuedSynchronizer2:共享模式与基于Condition的等待/通知机制实现
共享模式acquire实现流程 上文我们讲解了AbstractQueuedSynchronizer独占模式的acquire实现流程,本文趁热打铁继续看一下AbstractQueuedSynchroni ...
- 最短路问题之Bellman-ford算法
题目: 最短路:给定两个顶点,在以这两个点为起点和终点的路径中,边的权值和最小的路径.考虑权值为点之间的距离. 单源最短路问题,Bellman-ford算法 思路:每次循环检查所有边,可优化. 应用于 ...
- hadoop rpc协议客户端与服务端的交互流程
尽管这里是hadoop的rpc服务,但是hadoop还是做到了一次连接仅有一次认证.具体的流程待我慢慢道来. 客户端:这里我们假设ConnectionId对应的Connection并不存在.在调用ge ...
- Dubbo简介
1. Dubbo是什么? Dubbo是一个分布式服务框架,致力于提供高性能和透明化的RPC远程服务调用方案,以及SOA服务治理方案.简单的说,dubbo就是个服务框架,如果没有分布式的需求,其实是不需 ...
- async/await使用深入详解
async和await作为异步模型代码编写的语法糖已经提供了一段时间不过一直没怎么用,由于最近需要在BeetleX webapi中集成对Task方法的支持,所以对async和await有了深入的了解和 ...
- 『集群』007 如何测试Slithice源代码
如何测试Slithice源代码 直接测试 >你可以直接 进入 “集合编译区”,这里面 已经有 编译好的 所有程序集: >部署 配置数据库: >附加 集合编译区 中的 SQLServe ...
- 数据库~dotnetcore连接Mysql插入中文失败
到目录 在dotnetcore里,连接mysql数据,插入中文时出现无法识别,并提示插入失败的情况,分析后得知它是编码问题,即数据库编码问题,你的中文在数据表里无法被识别! 解决方法(一) 进行mys ...
- Vue2.0源码阅读笔记(一):选项合并
Vue本质是上来说是一个函数,在其通过new关键字构造调用时,会完成一系列初始化过程.通过Vue框架进行开发,基本上是通过向Vue函数中传入不同的参数选项来完成的.参数选项往往需要加以合并,主要有 ...