阿里云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不是瓜未熟 ...
随机推荐
- DataPipeline | PayPal庞姬桦:大数据在小微企业贷款上的运用
庞姬桦女士毕业于北京大学和美国哥伦比亚大学,目前担任PayPal公司消费者风险管理总监,负责通过大数据实现对互联网金融风险的侦测.跟踪.管控和防范.在加入PayPal之前,曾任职于渣打银行(中国)和美 ...
- 如何修复使用WSUS进行升级Win 10 更新1809的报错(0x8024200)
备注:该文档有另一个姊妹篇,介绍如何修复下游服务器一直有处于需要文件下载的状况. /* Style Definitions */ table.MsoNormalTable {mso-style-nam ...
- 一键解决更改计算机名后无法启动MSSQLSERVER服务问题
问题版本:SQL Server 2012. 解决办法:打开服务,Win + R运行services.msc,找到 SQL SERVER(MSSQLSERVER)服务右键->属性,切换至登录选项卡 ...
- IDEA zookeeper插件的使用
安装插件 file-settings-Plugins 搜索zookeeper,并安装,安装完成后重启IDEA 配置IP地址和端口 位于Other settings 中的zookeeper选项中配置 注 ...
- hdfs一直处于safemode模式
目前来看,导致hdfs一直处于safemode模式最直接的原因是已成功复制的块的比例没有达到默认值,块的损坏也会造成一直处于安全模式. 1)文件系统中有损坏的文件,使用fsck命令来查看 hadoop ...
- 页面结构化在 Android 上的尝试
本文来自于腾讯Bugly公众号(weixinBugly),未经作者同意,请勿转载,原文地址:https://mp.weixin.qq.com/s/M45DM5Ix7a2fmrsE8VPvxg 作者:b ...
- SpringBoot2.0 项目中使用事务
参考博客: SpringBoot开启事务常见坑点 另外注意手动回滚事务需要 (1)在业务层方法上添加注解 @Transactional (2)在需要回滚的地方添加代码: TransactionAspe ...
- asp.net core导出导入excel
使用NPOI导入导出excel,已经封装好Action可以直接调用 导出 效果图 使用方法 定义导出实体 class Student { public int Id { get; set; } pub ...
- 记一次尴尬的Java应用内存泄露排查
这星期被线上JVM内存占用不断增大的问题所困扰,自己提出了一些假设,然后去实施验证都一一失败了,有一些经验和教训在这里分享下. 之所以是尴尬,是最后因为修复了另一个看似不相关的问题导致内存不再上升,但 ...
- Java下载创建好的Excel模板
1.废话不多说,直接上源码 //从数据库取数据创建表格 private HSSFWorkbook exportStudentInfo(List<ExamStudentVo> student ...