为了简便财务总是要对照着别人发来的表格图片制作成自己的表格

效果图如下

整合的代码
  1. package com.xai.wuye.controller.api;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONException;
  5. import com.alibaba.fastjson.JSONObject;
  6. import com.xai.wuye.common.JsonResult;
  7. import com.xai.wuye.exception.ResultException;
  8. import com.xai.wuye.model.AParam
  9. import com.xai.wuye.service.CarService;
  10. import com.xai.wuye.util.HttpUtils;
  11. import org.apache.http.HttpResponse;
  12. import org.apache.http.util.EntityUtils;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.core.io.FileSystemResource;
  15. import org.springframework.http.HttpHeaders;
  16. import org.springframework.http.MediaType;
  17. import org.springframework.http.ResponseEntity;
  18. import org.springframework.scheduling.annotation.EnableAsync;
  19. import org.springframework.stereotype.Controller;
  20. import org.springframework.web.bind.annotation.RequestMapping;
  21. import org.springframework.web.bind.annotation.RequestParam;
  22. import org.springframework.web.bind.annotation.ResponseBody;
  23. import org.springframework.web.multipart.MultipartFile;
  24. import java.io.*;
  25. import java.util.Date;
  26. import java.util.HashMap;
  27. import java.util.Map;
  28. import static org.apache.tomcat.util.codec.binary.Base64.encodeBase64;
  29. @Controller
  30. @EnableAsync
  31. @RequestMapping("/api/ocr")
  32. public class AliOCRImages {
  33. @Autowired
  34. CarService carService;
  35.    private String OcrPath = "/home/runApp/car/orc/";
  36. @ResponseBody
  37. @RequestMapping("table")
  38. public JsonResult getFirstLicence(@RequestParam(value = "file", required = false) MultipartFile file) {
  39. if (file == null || file.isEmpty()||file.getSize() > 1204*1204*3)
  40. throw new ResultException(0,"文件为null,且不能大于3M");
  41. String filename = file.getOriginalFilename();
  42. String filepath = OcrPath+"temp/"+filename;
  43. File newFile = new File(filepath);
  44. try {
  45. file.transferTo(newFile);
  46. String host = "https://form.market.alicloudapi.com";
  47. String path = "/api/predict/ocr_table_parse";
  48.            // 输入阿里的code
  49.            String appcode = "4926a667ee6c41329c278361*****";
  50. String imgFile = "图片路径";
  51. Boolean is_old_format = false;//如果文档的输入中含有inputs字段,设置为True, 否则设置为False
  52. //请根据线上文档修改configure字段
  53. JSONObject configObj = new JSONObject();
  54. configObj.put("format", "xlsx");
  55. configObj.put("finance", false);
  56. configObj.put("dir_assure", false);
  57. String config_str = configObj.toString();
  58. // configObj.put("min_size", 5);
  59. //String config_str = "";
  60. String method = "POST";
  61. Map<String, String> headers = new HashMap<String, String>();
  62. //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
  63. headers.put("Authorization", "APPCODE " + appcode);
  64. Map<String, String> querys = new HashMap<String, String>();
  65. // 对图像进行base64编码
  66. String imgBase64 = "";
  67. try {
  68. byte[] content = new byte[(int) newFile.length()];
  69. FileInputStream finputstream = new FileInputStream(newFile);
  70. finputstream.read(content);
  71. finputstream.close();
  72. imgBase64 = new String(encodeBase64(content));
  73. } catch (IOException e) {
  74. e.printStackTrace();
  75. return null;
  76. }
  77. // 拼装请求body的json字符串
  78. JSONObject requestObj = new JSONObject();
  79. try {
  80. if(is_old_format) {
  81. JSONObject obj = new JSONObject();
  82. obj.put("image", getParam(50, imgBase64));
  83. if(config_str.length() > 0) {
  84. obj.put("configure", getParam(50, config_str));
  85. }
  86. JSONArray inputArray = new JSONArray();
  87. inputArray.add(obj);
  88. requestObj.put("inputs", inputArray);
  89. }else{
  90. requestObj.put("image", imgBase64);
  91. if(config_str.length() > 0) {
  92. requestObj.put("configure", config_str);
  93. }
  94. }
  95. } catch (JSONException e) {
  96. e.printStackTrace();
  97. }
  98. String bodys = requestObj.toString();
  99. try {
  100. /**
  101. * 重要提示如下:
  102. * HttpUtils请从
  103. * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
  104. * 下载
  105. *
  106. * 相应的依赖请参照
  107. * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
  108. */
  109. HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
  110. int stat = response.getStatusLine().getStatusCode();
  111. if(stat != 200){
  112. System.out.println("Http code: " + stat);
  113. System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message"));
  114. System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
  115. return null;
  116. }
  117. String res = EntityUtils.toString(response.getEntity());
  118. JSONObject res_obj = JSON.parseObject(res);
  119. Long fileName = System.currentTimeMillis();
  120. if(is_old_format) {
  121. JSONArray outputArray = res_obj.getJSONArray("outputs");
  122. String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
  123. JSONObject out = JSON.parseObject(output);
  124. System.out.println(out.toJSONString());
  125. }else{
  126. String tmp_base64path = OcrPath + fileName;
  127. File tmp_base64file = new File(tmp_base64path);
  128. if(!tmp_base64file.exists()){
  129. tmp_base64file.getParentFile().mkdirs();
  130. }
  131. tmp_base64file.createNewFile();
  132. // write
  133. FileWriter fw = new FileWriter(tmp_base64file, true);
  134. BufferedWriter bw = new BufferedWriter(fw);
  135. bw.write(res_obj.getString("tables"));
  136. bw.flush();
  137. bw.close();
  138. fw.close();
  139. String exelFilePath = OcrPath + fileName + "_1.xlsx";
  140. Runtime.getRuntime().exec("touch "+exelFilePath).destroy();
  141. Process exec = Runtime.getRuntime().exec("sed -i -e 's/\\\\n/\\n/g' " + tmp_base64path);
  142. exec.waitFor();
  143. exec.destroy();
  144. Process exec1 = null;
  145. String[] cmd = { "/bin/sh", "-c", "base64 -d " + tmp_base64path + " > " + exelFilePath };
  146. exec1 = Runtime.getRuntime().exec(cmd);
  147. exec1.waitFor();
  148. exec1.destroy();
  149. return JsonResult.success(fileName);
  150. }
  151. } catch (Exception e) {
  152. e.printStackTrace();
  153. }
  154. } catch (IOException e) {
  155. e.printStackTrace();
  156. }
  157. return null;
  158. }
  159. @ResponseBody
  160. @RequestMapping("getId")
  161. public ResponseEntity<FileSystemResource> getFirstLicence(String id) {
  162. String exelFilePath = OcrPath + id + "_1.xlsx";
  163. return export(new File(exelFilePath));
  164. }
  165. public ResponseEntity<FileSystemResource> export(File file) {
  166. if (file == null) {
  167. return null;
  168. }
  169. HttpHeaders headers = new HttpHeaders();
  170. headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
  171. headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".xls");
  172. headers.add("Pragma", "no-cache");
  173. headers.add("Expires", "0");
  174. headers.add("Last-Modified", new Date().toString());
  175. headers.add("ETag", String.valueOf(System.currentTimeMillis()));
  176. return ResponseEntity
  177. .ok()
  178. .headers(headers)
  179. .contentLength(file.length())
  180. .contentType(MediaType.parseMediaType("application/octet-stream"))
  181. .body(new FileSystemResource(file));
  182. }
  183. public static JSONObject getParam(int type, String dataValue) {
  184. JSONObject obj = new JSONObject();
  185. try {
  186. obj.put("dataType", type);
  187. obj.put("dataValue", dataValue);
  188. } catch (JSONException e) {
  189. e.printStackTrace();
  190. }
  191. return obj;
  192. }
  193. }

大功告成

  • 以下是静态页面代码
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <!-- import CSS -->
  6. <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  7. <title>table</title>
  8. </head>
  9. <body>
  10. <div id="app">
  11. <el-upload
  12. class="upload-demo"
  13. drag
  14. action="https://www.***.com/car/api/ocr/table"
  15. :file-list="imagelist"
  16. :on-preview="pre"
  17. >
  18. <i class="el-icon-upload"></i>
  19. <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
  20. <div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
  21. </el-upload>
  22. <div class="img-content" v-for="(item,key) in imagelist" :key="key">
  23. <img :src="item.url">
  24. <div class="name">
  25. <div>{{ item.name }}</div>
  26. <el-button type="text" @click="handleFileName(item,key)">修改名字</el-button>
  27. </div>
  28. <!-- 删除icon -->
  29. <div class="del">
  30. <i @click="handleFileRemove(item,key)" class="el-icon-delete2"></i>
  31. </div>
  32. <!-- 放大icon -->
  33. <div class="layer" @click="handleFileEnlarge(item.url)">
  34. <i class="el-icon-view"></i>
  35. </div>
  36. </div>
  37. </div>
  38. </body>
  39. <!-- import Vue before Element -->
  40. <script src="https://unpkg.com/vue/dist/vue.js"></script>
  41. <!-- import JavaScript -->
  42. <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  43. <script>
  44. new Vue({
  45. el: '#app',
  46. data: function() {
  47. return {
  48. visible: false,
  49. imagelist: [
  50. ]
  51. }
  52. },
  53. methods: {
  54. pre(res) {
  55. console.log(res.response.msg)
  56. window.open("https://www.***.com/api/ocr/getId?id="+res.response.data);
  57. }
  58. }
  59. })
  60. </script>
  61. </html>

使用阿里云的图片识别成表格ocr(将图片表格转换成excel)的更多相关文章

  1. WPF中实现图片文件转换成Visual对象,Viewport3D对象转换成图片

    原文:WPF中实现图片文件转换成Visual对象,Viewport3D对象转换成图片 1.图片文件转换成Visual对象 private Visual CreateVisual(string imag ...

  2. 转换成json字符串,与json字符串转换成java类型都要先转换成json对象

    转换成json字符串,与json字符串转换成java类型都要先转换成json对象

  3. 将一个字符串中的大写字母转换成小写字母,小写字母转换成大写字母(java)

    背景:刚刚学到java的String和StringBuffer类,遇到如标题所示的题. 要求:必须要用到String类的toUpperCase方法和toLowerCase方法 思路:用到StringB ...

  4. C# DataTable转换成实体列表 与 实体列表转换成DataTable

    /// <summary> /// DataTable转换成实体列表 /// </summary> /// <typeparam name="T"&g ...

  5. Java对象转换成xml对象和Java对象转换成JSON对象

    1.把Java对象转换成JSON对象 apache提供的json-lib小工具,它可以方便的使用Java语言来创建JSON字符串.也可以把JavaBean转换成JSON字符串. json-lib的核心 ...

  6. json字符串转换成json对象,json对象转换成字符串,值转换成字符串,字符串转成值

    一.json相关概念 json,全称为javascript object notation,是一种轻量级的数据交互格式.采用完全独立于语言的文本格式,是一种理想的数据交换格式. 同时,json是jav ...

  7. 【tp5】索引数组转成关联数组 ( $a=[],转换成 $a['aa'=>2,'bb'=>'3c'] )

    概念: 索引数组 ==== >>>$arr = []; 关联数组 ====>>> $arr = [ 'orange'=>1,'apple'=>'good ...

  8. 图片识别文字, OCR

    文章引用自: https://www.cnblogs.com/stone_w/archive/2011/10/08/2202397.html 方式一.Asprise-OCR的使用. Asprise-O ...

  9. java 中文转换成Unicode编码和Unicode编码转换成中文

    转自:一叶飘舟 http://blog.csdn.net/jdsjlzx/article/details/ package lia.meetlucene; import java.io.IOExcep ...

  10. iOS中NSString转换成HEX(十六进制)-NSData转换成int

    http://www.2cto.com/kf/201402/281501.html 1 2 3 4 5 6 NSString *str = @"0xff055008"; //先以1 ...

随机推荐

  1. User Profile Service服务未能登录,无法登录

    不知你是否遇到这样的问题,某一天你打开PC,开机正常,可当你输入正确的密码回车,却发现Vista或Win7拒绝让你登录,提示"User Profile Service 服务未能登录.无法加载 ...

  2. 在MFC中使用按下按钮出现选择文件对话框,选中一个指定文件,并将其地址显示到指定的编辑框中

    其中,我们选择的文件后缀名为.xlsx,以只读和写操作方式,在所有的文件中选择.xlsl文档 CFileDialog dlg(true, _T(".xlsx"), NULL, OF ...

  3. LOJ_6045_「雅礼集训 2017 Day8」价 _最小割

    LOJ_6045_「雅礼集训 2017 Day8」价 _最小割 描述: 有$n$种减肥药,$n$种药材,每种减肥药有一些对应的药材和一个收益. 假设选择吃下$K$种减肥药,那么需要这$K$种减肥药包含 ...

  4. BZOJ_2595_[Wc2008]游览计划_斯坦纳树

    BZOJ_2595_[Wc2008]游览计划_斯坦纳树 题意: 分析: 斯坦纳树裸题,有几个需要注意的地方 给出矩阵,不用自己建图,但枚举子集转移时会算两遍,需要减去当前点的权值 方案记录比较麻烦,两 ...

  5. zabbix监控elasticsearch

    1.环境概述 虚拟机系统:CentOS Linux release 7.3.1611 (Core) 宿主机系统:Mac Sierra version 10.12.3 nginx:1.10.3 php: ...

  6. Oracle系列-锁表与解锁解决方案(基础版)

    [Oracle锁表查询和解锁解决方案] 一.了解原因(借鉴整理) 数据库操作语句的分类 DDL:数据库模式定义语言,关键字:createDML:数据操纵语言,关键字:Insert.delete.upd ...

  7. 我的微服务观,surging 2.0将会带来多大的改变

    Surging 自2017年6月16日开源以来,已收到不少公司的关注或者使用,其中既有以海克斯康超大型等外企的关注,也不乏深圳泓达康.重庆金翅膀等传统行业的正式使用,自2019年年初,surging2 ...

  8. 流程控制之while循环

    目录 语法(掌握) while+break while+continue while循环的嵌套(掌握) tag控制循环退出(掌握) while+else(了解) 语法(掌握) 循环就是一个重复的过程, ...

  9. Python爬虫入门教程 59-100 python爬虫高级技术之验证码篇5-极验证识别技术之二

    图片比对 昨天的博客已经将图片存储到了本地,今天要做的第一件事情,就是需要在两张图片中进行比对,将图片缺口定位出来 缺口图片 完整图片 计算缺口坐标 对比两张图片的所有RBG像素点,得到不一样像素点的 ...

  10. 给女朋友讲解什么是Optional【JDK 8特性】

    前言 只有光头才能变强 前两天带女朋友去图书馆了,随手就给她来了一本<与孩子一起学编程>的书,于是今天就给女朋友讲解一下什么是Optional类. 至于她能不能看懂,那肯定是看不懂的.(学 ...