excel 中ActiveX 工具 中的textbox  ,以及公式 解析后为emf 图片, 

 emf 转图片(解决图片上部分显示不全问题)  图片转文字

/***************************
*<pre>
* @Project Name : base-case-test-service
* @Package : com.icil.pinpal.test
* @File Name : XX
* @Author : Sea
* @Date : 9/28/22 2:13 PM
* @Purpose :
* @History :
*</pre>
***************************/ import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.poi.util.IOUtils;
import org.freehep.graphicsio.emf.EMFInputStream;
import org.freehep.graphicsio.emf.EMFRenderer;
import org.freehep.graphicsio.emf.EMFTag;
import org.freehep.util.io.Tag;
import org.junit.Test; import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.List; /***************************
*<pre>
* <dependency>
* <groupId>net.sourceforge.tess4j</groupId>
* <artifactId>tess4j</artifactId>
* <version>4.6.1</version>
* </dependency>
* <dependency>
* <groupId>commons-httpclient</groupId>
* <artifactId>commons-httpclient</artifactId>
* <version>3.1</version>
*  </dependency>
* <dependency>
* <groupId>org.freehep</groupId>
* <artifactId>freehep-graphicsio-emf</artifactId>
* <version>2.4</version>
* </dependency>
* @Project Name : base-case-test-service
* @Package : com.sea.base.test
* @File Name : ImageUtils
* @Author : Sea
* @Mail : lshan523@163.com
* @Date : 2022/9/19 16:09
* @Purpose :1.emf 文件转 png
*  2.图片转为文字
*  3.http 表单提交
* 4: 反射工具
* @History :
*</pre>
***************************/
@Slf4j
public class ImageUtils { private static ITesseract instance = null;
static
{
instance = new Tesseract();
instance.setDatapath("/home/sea/Desktop/FTP/tessdata-main");
instance.setLanguage("chi_sim+eng");
} /**
* 直接将emf 文件流转成文本
* @param emfBytes
*/
public static String emf2text(byte[] emfBytes) throws Exception
{
String tmpPath = "/tmp/"+UUID.randomUUID().toString().replaceAll("-", "")+".png";
File pngFile = emfToPng(emfBytes, tmpPath);
String text = img2Text(pngFile,true);
deleteFile(pngFile);
return text;
} public static String emf2text(File emfFile) throws Exception
{
byte[] emfBytes = file2byte(emfFile);
// emfFile.delete();
String tmpPath = "/tmp/"+UUID.randomUUID().toString().replaceAll("-", "")+".png";
File pngFile = emfToPng(emfBytes, tmpPath);
String text = img2Text(pngFile,true);
deleteFile(pngFile);
return text;
} /**
* @param picFile
* @return
* @throws Exception
*/
public static String img2Text(File picFile,boolean isBy3rd) throws Exception
{
String text = null;
if(isBy3rd==true)
{
String url= "http://192.168.186.129:5000/ocrimg";
HashMap<String, Object> formData = new HashMap<String, Object>() {{
put("language", "eng+chi_sim");
put("img", picFile);
}};
String s = postFormData(url, formData);
return s;
}else //local
{
BufferedImage img = ImageIO.read(picFile);
text = instance.doOCR(img);
}
return text;
} /**
* @param inEmfPath
* @param outPngPath
* @return
* @throws Exception
*/
public static File emfToPng( String inEmfPath,String outPngPath) throws Exception{
byte[] bytes = file2byte(inEmfPath);
// deleteFile(inEmfPath);
return emfToPng(bytes,outPngPath);
} /**
* 可以解决图片上部分显示不全问题
* @param emfBytes
* @param outPngPath
* @return
*/
public static File emfToPng( byte[] emfBytes,String outPngPath){
EMFInputStream eis = null;
File outFile = null;
try {
eis = new EMFInputStream(new ByteArrayInputStream(emfBytes), EMFInputStream.DEFAULT_VERSION);
EMFRenderer emfRender = new EMFRenderer(eis);
final int height = (int) eis.readHeader().getBounds().getHeight()+30;
final int width = (int) eis.readHeader().getBounds().getWidth()+30;
final BufferedImage bufImage = new BufferedImage(width, height ,BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2 = bufImage.createGraphics();
// g2.setBackground(Color.RED);
// g2.drawString("嘻嘻嘻嘻",1,10); //可以添加水印
// emfRender.paint(g2);//原生方法<有问题,数据显示不全>
paint(g2,emfRender);
outFile = new File(outPngPath);
ImageIO.write(bufImage, "png",outFile);
return outFile; } catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(eis);
// deleteFile(outFile);
}
return outFile;
} /**
* @param g2
* @param emfRenderer
* @throws Exception
*/
public static void paint(Graphics2D g2, EMFRenderer emfRenderer) throws Exception{
emfRenderer.setViewportOrigin(new Point(-10, -15));
emfRenderer.setWindowOrigin(new Point(10, 10));
// emfRenderer.setBrushOrigin(new Point(10, 10)); g2.setBackground(Color.black); setFiledValue(emfRenderer,"g2",g2);
Shape clip = g2.getClip();
AffineTransform at = g2.getTransform();
Map hints = g2.getRenderingHints();
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
setFiledValue(emfRenderer,"initialTransform",g2.getTransform());
setFiledValue(emfRenderer,"path",null);
setFiledValue(emfRenderer,"figure",null);
setFiledValue(emfRenderer,"meterLimit",10);
setFiledValue(emfRenderer,"windingRule",0);
setFiledValue(emfRenderer,"bkMode",2);
setFiledValue(emfRenderer,"useCreatePen",true);
setFiledValue(emfRenderer,"scaleMode",4);
// setFiledValue(emfRenderer,"windowOrigin",null);
// setFiledValue(emfRenderer,"viewportOrigin",null);
setFiledValue(emfRenderer,"windowSize",null);
setFiledValue(emfRenderer,"viewportSize",null);
setFiledValue(emfRenderer,"mapModeIsotropic",false);
setFiledValue(emfRenderer,"mapModeTransform",AffineTransform.getScaleInstance(emfRenderer.TWIP_SCALE, emfRenderer.TWIP_SCALE));
runMethod(emfRenderer,"resetTransformation",g2,Graphics2D.class);
setFiledValue(emfRenderer,"initialClip",g2.getClip());
Vector tags = (Vector)getPrivateFiledValue(emfRenderer, "tags");
for(int i = 0; i < tags.size(); ++i) {
Tag tag = (Tag)tags.get(i);
if (tag instanceof EMFTag) {
((EMFTag)tags.get(i)).render(emfRenderer);
} else {
log.warn("unknown tag: " + tag);
}
}
g2.setRenderingHints(hints);
g2.setTransform(at);
g2.setClip(clip);
} /**
* <dependency>
* <groupId>commons-httpclient</groupId>
* <artifactId>commons-httpclient</artifactId>
* <version>3.1</version>
*  </dependency>
* @param url
* @param formData
* @Author Sea
* @return
*/
public static String postFormData(String url,Map<String,Object> formData)
{
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(url);
try{
List<Part> formArgsList = new ArrayList<>();
for (Map.Entry<String, Object> kv :formData.entrySet()) {
String key = kv.getKey();
Object value = kv.getValue();
if(value instanceof File){
FilePart fp = new FilePart(key, (File) value);
fp.setCharSet("utf-8");
formArgsList.add(fp);
}else
{
formArgsList.add(new StringPart(key, value+"", "UTF-8"));
}
}
Part[] parts = formArgsList.toArray(new Part[formArgsList.size()]);
MultipartRequestEntity entity = new MultipartRequestEntity(parts, new HttpMethodParams());
post.setRequestEntity(entity);
client.executeMethod(post);
//释放连接,以免超过服务器负荷
String responseBodyAsString = post.getResponseBodyAsString();
return responseBodyAsString;
}
catch (Exception e)
{
e.printStackTrace();
}finally {
//释放连接,以免超过服务器负荷
post.releaseConnection();
}
return null;
} public static void deleteFile(File file){
if(file!=null&&file.exists()){
file.delete();
}
}
/**
* @param filePath
* @return
*/
public static byte[] file2byte(String filePath)throws Exception
{
File file = new File(filePath);
byte[] bytes = file2byte(file);
return bytes;
}
/**
* @param file
* @return
*/
public static byte[] file2byte(File file) throws Exception
{
FileInputStream fis = new FileInputStream(file);
byte[] bytes = org.apache.commons.io.IOUtils.toByteArray(fis);
fis.close();
return bytes;
} /**
* @param obj
* @param fileName
* @param value
* @throws Exception
*/
public static void setFiledValue(Object obj, String fileName, Object value) throws Exception {
Field name = obj.getClass().getDeclaredField(fileName);
name.setAccessible(true);
name.set(obj,value);
}
/**
* 获取类的私有属性 : eg:name
* @param objClss
* @param fileName
* @throws Exception
*/
public static Object getPrivateFiledValue(Object objClss, String fileName) throws Exception {
Field name = objClss.getClass().getDeclaredField(fileName);
name.setAccessible(true);
Object o = name.get(objClss);
return o;
} /**
* @param obj
* @param methodName
* @param args
* @param parameterTypes
* @return
* @throws Exception
*/
public static Object runMethod(Object obj, String methodName, Object args,Class<?>... parameterTypes) throws Exception {
Method declaredMethod = obj.getClass().getDeclaredMethod(methodName, parameterTypes);
declaredMethod.setAccessible(true);
Object invoke = declaredMethod.invoke(obj, args);
return invoke;
} @Test
public void testOcr() throws Exception {
String emfPath = "/home/sea/Desktop/FTP/TextBox2.emf";
String outPath ="/home/sea/CCCCCCCCCCC/AAAA_svn_new_AAAA/base-case-test-service/src/test/resources/TextBox1.png";
emfToPng(emfPath ,outPath );
BufferedImage img = ImageIO.read(new File(outPath));
ITesseract instance = new Tesseract();
instance.setDatapath("/home/sea/Desktop/FTP/tessdata-main");
instance.setLanguage("chi_sim+eng");
String result = instance.doOCR(img);
System.err.println(result); } }

ImageUtils excel 中 emf 转图片(解决图片上部分显示不全问题)图片转文字的更多相关文章

  1. javascript DOM(2) 一个网页上切换显示不同的图片或文本

    摘自: javascript DOM 编程艺术 1. 在一个网页上切换显示不同的图片 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Tran ...

  2. 解决XP系统任务管理器显示不全

    我们在使用电脑的时候有的时候打开任务管理器会发现任务管理器显示不全. 当碰到这种情况怎么解决呢?任务管理器显示不全的原因又是那些呢? 这里就来为大家分享下为什么任务管理器会显示不全以及如何解决这个问题 ...

  3. OAF_文件系列4_实现OAF上传显示数据库动态图片Image(案例)

    20150805 Created By BaoXinjian

  4. 在Vue项目中,添加的背景图片在服务器上不显示,如何处理

    遇到的问题: 在vue项目开发过程中,我们常常会在页面中添加背景图片.可是当我们在样式中添加了背景图片,编译打包部署到服务器上时,发现图片并不能显示出来,这是为什么呢~~~ 我们一般写的css样式如下 ...

  5. vue中图片返回404时,显示默认的图片

    图片返回404时候的处理 <img :src="userMsg.portrait" ref="img" alt=""> _thi ...

  6. img标签中的图片加载异常时显示默认的图片

    备忘:

  7. linux上不能显示Jfreechart的图片文件

     出现错误: Jan 23, 2015 4:19:21 PM org.apache.catalina.core.StandardWrapperValve invokeSEVERE: Servlet.s ...

  8. JS使用默认图片代替页面上无法显示的图片

    1.js方法: function replaceErrorImg(obj) { obj.src="images/common/error.bmp"; } 2.jquery绑定 $( ...

  9. 修改DEDECMS文章标题长度,解决DEDECMS文章标题显示不全

    dedecms系统使用过程中,常遇到输入的标题原本输入的字数跟保存成功后的数字长度不一样,这个是因为 织梦dedecms系统默认的文章标题字数限制是60,也就是只能输入30个汉字,超过的会自动截断删除 ...

  10. 解决TextView最后一行显示不全

    public class MultilineTextView extends TextView { private boolean calculatedLines = false; public Mu ...

随机推荐

  1. 通过python程序让MySQL利用binlog恢复误操作数据

    MySQL利用binlog恢复误操作数据 在人工手动进行一些数据库写操作的时候(比方说数据订正),尤其是一些不可控的批量更新或删除,通常都建议备份后操作.不过不怕万一,就怕一万,有备无患总是好的.在线 ...

  2. CCF 202012-1 期末预测之安全指数

    #include <iostream> //#include <bits/stdc++.h> #include <string> using namespace s ...

  3. CF960G

    首先我们考虑$n$的情况,显然以$n$为分界线可以将整个序列分成两部分,就像这样: . 那么我们考虑:在这个东西前面才会有前缀最大的统计,在这个东西后面才会有后缀最大的统计 这样就剩下了$n-1$个元 ...

  4. Unity中常用的几种读取本地文件方式

    使用的命名空间如下 using LitJson;using System.Collections.Generic;using System.IO;using System.Text;using Uni ...

  5. You Don't Know JS阅读笔记

    JS特性查漏补缺 [1,2,3]=="1,2,3" //true 前者会隐式转换,用逗号组合成字符串 212>'22' //true 有一个值不是number就会隐式转换成n ...

  6. Windows修改用户名

    修改用户名 右键此电脑>>管理>>本地用户和组>>用户,找到要修改的用户,重命名 修改用户home目录名 1.激活管理员账号 右键此电脑>>管理> ...

  7. 图论之最小生成树问题(kruskal)

    最近有几位同学催我更新,于是来摸摸鱼,来讲一下最小生成树问题. 所谓最小生成树(MST),就是在一张无向带权图中的一棵经过所有节点,边权和最小的一棵树.在实际生活中,可以运用于城镇之间的修路上. 对于 ...

  8. 【相邻父元素选择器】为啥p元素里面的h3也被选择了呢?求赐教

    <!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>& ...

  9. idea中ueditor的入门

    首先在https://github.com/fex-team/ueditor下载ueditor1_4_3_3-utf8-jsp.zip:解压去掉里边jsp中的bin目录放到项目中的webapp中: 添 ...

  10. Spring Boot中使用过滤器和拦截器

    过滤器(Filter)和拦截器(Interceptor)是Web项目中常用的两个功能,本文将简单介绍在Spring Boot中使用过滤器和拦截器来计算Controller中方法的执行时长,并且简单对比 ...