首页 > 其他分享 >ImageUtils   excel 中 emf 转图片(解决图片上部分显示不全问题)  图片转文字

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

时间:2022-09-29 15:55:30浏览次数:55  
标签:emf g2 ImageUtils param String emfRenderer new import 图片

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

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

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 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         : [email protected]
 * @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 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; } /** * @param picFile * @return * @throws Exception */ public 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)); 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/CCCCCCCCCCC/AAAA_svn_new_AAAA/base-case-test-service/src/test/resources/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); } }

 

标签:emf,g2,ImageUtils,param,String,emfRenderer,new,import,图片
From: https://www.cnblogs.com/lshan/p/16741860.html

相关文章

  • 物理层图片
    1.  2. ......
  • vue +echarts+ docxtemplater导出word和图表图片
    1.下载插件//--安装docxtemplaternpminstalldocxtemplaterpizzip--save//--安装jszip-utilsnpminstalljszip-utils--save//--安装jszipnpminstallj......
  • 9. HTML-- 插入图片:<img>标签
    1.前言一图胜千言,图片比文字更具表现力,恰当地使用图片可以让网页更加精美。HTML使用<img>标签插入图片,img是image的简称。<img>是自闭和标签,只包含属性,没有结束标......
  • 网络图片转base64
    /**        * 网络图片转base64        * @param src        * @return        * @throws Exception     ......
  • 上传到Nginx的图片文件如何拥有可读的权限
    描述使用springmvc做了一个文件上传的功能,上传到nginx目录下的一个文件夹,但是通过目录访问的时候却报403的错误去服务器查看了一下文件的权限,发现没有可读权限,于是定位......
  • 3款大屏播放软件,用法很详细,用于大屏幕播放视频和图片
    要在展厅或户外的LED大屏幕上长时间循环播放视频或图片,就需要用到大屏播放软件,笔者整理几款好用的给大家。一、动屏大屏播放软件特点这款软件的特点是配置简单,界面美观,即插......
  • JDK8的base64编解码、图片转base64
    importjava.io.ByteArrayOutputStream;importjava.io.FileInputStream;importjava.io.InputStream;importjava.nio.charset.StandardCharsets;importjava.util.Base64......
  • vue 遍历图片渲染
    原文链接:https://blog.csdn.net/sywdebug/article/details/120763271举例说明获取目录下的文件名新创建一个vue项目,获取views目录下的以.vue结尾的文件的文件名mounted......
  • element-ui 上传文件后点击图片实现预览效果
    背景在我们上传文件后我们希望点击文件实现预览效果进行确认或者其他操作。方式1:可以使用element-ui的upload组件+dialog+image组件解决,示例代码如下:<el-uploada......
  • 在图片不被裁剪时opencv绕图片中任意点旋转任意角度
    opencv绕图片中任意角度旋转任意角度  最近在做项目需要把把图片绕图片中任意点旋转任意角度,考虑到自己旋转需要编写插值算法,所以想到了用opencv,但是网上都是围绕图片中......