自己用到记录下,方便下次使用。
wmf-svg-png
相关maven依赖如下
<dependency><groupId>org.apache.xmlgraphics</groupId><artifactId>batik-codec</artifactId><version>1.7</version></dependency>
示例代码如下
public static void main(String[] args) {// wmf 本地路径String wmfPath = "ceshi.wmf";// svg 本地临时路径String svgPath = "ceshi.svg";// png 本地临时路径String pngPath = "ceshi.png";// 是否替换符号字体boolean replaceSymbolFont = false;try {InputStream in = new FileInputStream(wmfPath);WmfParser parser = new WmfParser();final SvgGdi gdi = new SvgGdi(false);gdi.setReplaceSymbolFont(replaceSymbolFont);parser.parse(in, gdi);OutputStream out = null;try {out = new FileOutputStream(svgPath);if (svgPath.endsWith(".svgz")) {out = new GZIPOutputStream(out);}gdi.write(out);} finally {if (out != null) out.close();}// svg 转 pngFile svgFile = new File(svgPath);File pngFile = new File(pngPath);TranscoderInput transIn = new TranscoderInput(new FileInputStream(svgFile));TranscoderOutput transOut = new TranscoderOutput(new FileOutputStream(pngFile));JPEGTranscoder pngTranscoder = new JPEGTranscoder();pngTranscoder.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,new Float(.8));System.out.println("开始转png");//设置png画质精度0-1之间pngTranscoder.transcode(transIn, transOut);System.out.println("png成功");} catch (Exception e) {e.printStackTrace();}}
emf-png
需要导入org.apache.poi包 (最好是5.0.0以上版本,转出效果好点)
public static void main(String[] args) {// wmf本地路径String emfPath = "ceshi.emf";// png路径String pngPath = "ceshi.png";File emfFile = new File(emfPath);try {FileInputStream fis = new FileInputStream(emfFile);// for EMF / EMF+HemfPicture emf = new HemfPicture(fis);Dimension2D dim = emf.getSize();int width = Units.pointsToPixel(dim.getWidth());// keep aspect ratio for heightint height = Units.pointsToPixel(dim.getHeight());double max = Math.max(width, height);if (max > 1500) {width *= 1500 / max;height *= 1500 / max;}BufferedImage bufImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);Graphics2D g = bufImg.createGraphics();g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);emf.draw(g, new Rectangle2D.Double(0, 0, width, height));g.dispose();// 保存图片ImageIO.write(bufImg, "PNG", new File(pngPath));// 关闭流if (fis != null)fis.close();} catch (IOException e) {e.printStackTrace();log.info("emf转png出现异常!");}}