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

效果图如下

整合的代码
package com.xai.wuye.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.xai.wuye.common.JsonResult;
import com.xai.wuye.exception.ResultException;
import com.xai.wuye.model.AParam
import com.xai.wuye.service.CarService;
import com.xai.wuye.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; import static org.apache.tomcat.util.codec.binary.Base64.encodeBase64; @Controller
@EnableAsync
@RequestMapping("/api/ocr")
public class AliOCRImages { @Autowired
CarService carService;    private String OcrPath = "/home/runApp/car/orc/"; @ResponseBody
@RequestMapping("table")
public JsonResult getFirstLicence(@RequestParam(value = "file", required = false) MultipartFile file) {
if (file == null || file.isEmpty()||file.getSize() > 1204*1204*3)
throw new ResultException(0,"文件为null,且不能大于3M"); String filename = file.getOriginalFilename();
String filepath = OcrPath+"temp/"+filename;
File newFile = new File(filepath);
try {
file.transferTo(newFile); String host = "https://form.market.alicloudapi.com";
String path = "/api/predict/ocr_table_parse";            // 输入阿里的code
           String appcode = "4926a667ee6c41329c278361*****";
String imgFile = "图片路径";
Boolean is_old_format = false;//如果文档的输入中含有inputs字段,设置为True, 否则设置为False
//请根据线上文档修改configure字段
JSONObject configObj = new JSONObject();
configObj.put("format", "xlsx");
configObj.put("finance", false);
configObj.put("dir_assure", false);
String config_str = configObj.toString();
// configObj.put("min_size", 5);
//String config_str = ""; String method = "POST";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode); Map<String, String> querys = new HashMap<String, String>(); // 对图像进行base64编码
String imgBase64 = "";
try { byte[] content = new byte[(int) newFile.length()];
FileInputStream finputstream = new FileInputStream(newFile);
finputstream.read(content);
finputstream.close();
imgBase64 = new String(encodeBase64(content));
} catch (IOException e) {
e.printStackTrace();
return null;
}
// 拼装请求body的json字符串
JSONObject requestObj = new JSONObject();
try {
if(is_old_format) {
JSONObject obj = new JSONObject();
obj.put("image", getParam(50, imgBase64));
if(config_str.length() > 0) {
obj.put("configure", getParam(50, config_str));
}
JSONArray inputArray = new JSONArray();
inputArray.add(obj);
requestObj.put("inputs", inputArray);
}else{
requestObj.put("image", imgBase64);
if(config_str.length() > 0) {
requestObj.put("configure", config_str);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
String bodys = requestObj.toString(); try {
/**
* 重要提示如下:
* HttpUtils请从
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
* 下载
*
* 相应的依赖请参照
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
*/
HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
int stat = response.getStatusLine().getStatusCode();
if(stat != 200){
System.out.println("Http code: " + stat);
System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message"));
System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
return null;
} String res = EntityUtils.toString(response.getEntity());
JSONObject res_obj = JSON.parseObject(res);
Long fileName = System.currentTimeMillis();
if(is_old_format) { JSONArray outputArray = res_obj.getJSONArray("outputs");
String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
JSONObject out = JSON.parseObject(output);
System.out.println(out.toJSONString()); }else{ String tmp_base64path = OcrPath + fileName;
File tmp_base64file = new File(tmp_base64path);
if(!tmp_base64file.exists()){
tmp_base64file.getParentFile().mkdirs();
}
tmp_base64file.createNewFile(); // write
FileWriter fw = new FileWriter(tmp_base64file, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(res_obj.getString("tables"));
bw.flush();
bw.close();
fw.close(); String exelFilePath = OcrPath + fileName + "_1.xlsx";
Runtime.getRuntime().exec("touch "+exelFilePath).destroy();
Process exec = Runtime.getRuntime().exec("sed -i -e 's/\\\\n/\\n/g' " + tmp_base64path);
exec.waitFor();
exec.destroy(); Process exec1 = null;
String[] cmd = { "/bin/sh", "-c", "base64 -d " + tmp_base64path + " > " + exelFilePath };
exec1 = Runtime.getRuntime().exec(cmd);
exec1.waitFor();
exec1.destroy(); return JsonResult.success(fileName);
}
} catch (Exception e) {
e.printStackTrace();
} } catch (IOException e) {
e.printStackTrace();
} return null;
} @ResponseBody
@RequestMapping("getId")
public ResponseEntity<FileSystemResource> getFirstLicence(String id) {
String exelFilePath = OcrPath + id + "_1.xlsx";
return export(new File(exelFilePath));
} public ResponseEntity<FileSystemResource> export(File file) {
if (file == null) {
return null;
}
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".xls");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("Last-Modified", new Date().toString());
headers.add("ETag", String.valueOf(System.currentTimeMillis())); return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new FileSystemResource(file));
} public static JSONObject getParam(int type, String dataValue) {
JSONObject obj = new JSONObject();
try {
obj.put("dataType", type);
obj.put("dataValue", dataValue);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
} }

大功告成

  • 以下是静态页面代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- import CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<title>table</title>
</head>
<body>
<div id="app">
<el-upload
class="upload-demo"
drag
action="https://www.***.com/car/api/ocr/table"
:file-list="imagelist"
:on-preview="pre"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
<div class="img-content" v-for="(item,key) in imagelist" :key="key">
<img :src="item.url">
<div class="name">
<div>{{ item.name }}</div>
<el-button type="text" @click="handleFileName(item,key)">修改名字</el-button>
</div>
<!-- 删除icon -->
<div class="del">
<i @click="handleFileRemove(item,key)" class="el-icon-delete2"></i>
</div>
<!-- 放大icon -->
<div class="layer" @click="handleFileEnlarge(item.url)">
<i class="el-icon-view"></i>
</div>
</div>
</div>
</body>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
new Vue({
el: '#app',
data: function() {
return {
visible: false,
imagelist: [ ] }
},
methods: {
pre(res) {
console.log(res.response.msg)
window.open("https://www.***.com/api/ocr/getId?id="+res.response.data);
}
} })
</script>
</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. 理解channel 工作原理以及源码

    Go 的并发特性  goroutines: 独立执行每个任务,并可能并行执行 channels: 用于 goroutines 之间的通讯.同步 一个简单的事务处理的例子  对于下面这样的非并发的程序: ...

  2. 作为一个零基础的新手,如何系统的自学Java和JavaEE开发技术?

    其实这个问题很简单,我用最简单的语言给大家描述一下,学习一样东西就要了解这样东西学完了要干什么事情,有什么作用.然后就是应该学习哪些必要的内容,该如何运用得当的方法进行有效率的学习不至于自己摸不着头脑 ...

  3. Spark学习之键值对操作总结

    键值对 RDD 是 Spark 中许多操作所需要的常见数据类型.键值对 RDD 通常用来进行聚合计算.我们一般要先通过一些初始 ETL(抽取.转化.装载)操作来将数据转化为键值对形式.键值对 RDD ...

  4. js-刮刮卡效果,由jquery-eraser源码改的vue组件

    vue-eraser 一款用于vue刮刮卡的组件 github地址: vue-eraser npm地址: vue-eraser 在网上有看到过几个版本的组件,都有点问题 1.拉快了,就会断,连不起来( ...

  5. 前端笔记之Canvas

    一.Canvas基本使用 Canvas是HTML5的画布,Canvas算是“不务正业”的面向对象大总结,将面向对象玩极致. 算法为王!就是说canvas你不会,但是算法好,不怕写业务,不怕代码量,只要 ...

  6. 目标检测 anchor 理解笔记

    anchor在计算机视觉中有锚点或锚框,目标检测中常出现的anchor box是锚框,表示固定的参考框. 目标检测的任务: 在哪里有东西 难点: 目标的类别不确定.数量不确定.位置不确定.尺度不确定 ...

  7. video 属性和事件用法大全

    1.video 属性 <!-- video 不支持 IE8及以下版本浏览器,支持三种视频格式:MP4,WebM 和 Ogg --> <video src="test.mp4 ...

  8. 判空、判等、转码的StringUtil

    目录 StringUtil类 StringUtil类 import java.io.UnsupportedEncodingException; /** * 字符串工具 */ public class ...

  9. jqGrid 常用 总结 -2

    这次的总结是针对于一次bug,先说下我们遇到的问题,就是后台人员告诉我们添加数据到100条数据的时候,101条就看不到,当时我觉得就是没有分页的原因,所以我就以为在jqgrid中设置一个loadonc ...

  10. 实例分析Vue.js中 computed和methods不同机制

    在vue.js中,有methods和computed两种方式来动态当作方法来用的 1.首先最明显的不同 就是调用的时候,methods要加上() 2.我们可以使用 methods 来替代 comput ...