WMF EMF SVG PNG Java图片处理

代码就示例贴点

工作需要转换难度大的就是EMF的转换了

使用的是freehep包

有需要的话可留言,联系我
EMF2SVG
public  class EmfToSVG extends EMFConverter {
	public static void main(String[] args) {
		String[] file = new String[2];
		file[0] = "D:\\input.emf";
		
		if (file == null || file.length == 0 || file[0] == null || file[0].length() == 0) {
            System.out.println("usage: EMF2SVG imput.emf [output.svg]");
            return;
        }
        export(ImageConstants.SVG, file[0], file.length > 1 ? file[1] : null);
	}
	
	protected static void export(String type, String srcFileName, String destFileName) {
        try {
            List exportFileTypes = ExportFileType.getExportFileTypes(type);
            if (exportFileTypes == null || exportFileTypes.size() == 0) {
                System.out.println(
                    type + " library is not available. check your classpath!");
                return;
            }

            ExportFileType exportFileType = (ExportFileType) exportFileTypes.get(0);

            // read the EMF file
            EMFRenderer emfRenderer = new EMFRenderer(
                new EMFInputStream(
                    new FileInputStream(srcFileName)));

            // create the destFileName,
            // replace or add the extension to the destFileName
            if (destFileName == null || destFileName.length() == 0) {
                // index of the beginning of the extension
                int lastPointIndex = srcFileName.lastIndexOf(".");

                // to be sure that the point separates an extension
                // and is not part of a directory name
                int lastSeparator1Index = srcFileName.lastIndexOf("/");
                int lastSeparator2Index = srcFileName.lastIndexOf("\\");

                if (lastSeparator1Index > lastPointIndex ||
                    lastSeparator2Index > lastPointIndex) {
                    destFileName = srcFileName + ".";
                } else if (lastPointIndex > -1) {
                    destFileName = srcFileName.substring(
                        0, lastPointIndex + 1);
                }

                // add the extension
                destFileName += type.toLowerCase();
            }

            // TODO there is no possibility to use Constants of base class!
            /* create SVG properties*/
            Properties p = new Properties();
            p.put(SVGGraphics2D.EMBED_FONTS, Boolean.toString(false));
            p.put(SVGGraphics2D.CLIP, Boolean.toString(true));
            p.put(SVGGraphics2D.COMPRESS, Boolean.toString(false));
            p.put(SVGGraphics2D.TEXT_AS_SHAPES, Boolean.toString(false));
            p.put(SVGGraphics2D.FOR, "Freehep EMF2SVG");
            p.put(SVGGraphics2D.TITLE, srcFileName);

            EMFPanel emfPanel = new EMFPanel();
            emfPanel.setRenderer(emfRenderer);

            // TODO why uses this classes components?!
            exportFileType.exportToFile(
               new File(destFileName),
               emfPanel,
               emfPanel,
               p,
               "Freehep EMF converter");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


WmfToSvg

/**
 * @author LiJie
 * 将wmf转换为svg格式的
 * 
 * 
 */
public class WmfToSvg {
    public void converter(byte[] wmfBytes, String dest) throws Exception {
         InputStream in = new ByteArrayInputStream(wmfBytes);
         WmfParser parser = new WmfParser();
         final SvgGdi gdi = new SvgGdi(false);
         parser.parse(in, gdi);
         Document doc = gdi.getDocument();
         OutputStream out = new FileOutputStream(dest);
         if (dest.endsWith(".svgz")) {
              out = new GZIPOutputStream(out);
         }
         output(doc, out,dest);
    }
    public void convert(String file,String dest) throws Exception{
         InputStream in = new FileInputStream(file);    
         WmfParser parser = new WmfParser();
         final SvgGdi gdi = new SvgGdi(false);
         parser.parse(in, gdi);
         Document doc = gdi.getDocument();
         OutputStream out = new FileOutputStream(dest);
         if (dest.endsWith(".svgz")) {
             out = new GZIPOutputStream(out);
         }
         output(doc, out,dest);
    }
    public byte[] encodeConvert() {
         return null;
    }

    private void output(Document doc, OutputStream out,String dest) throws Exception {
         TransformerFactory factory = TransformerFactory.newInstance();
         Transformer transformer = factory.newTransformer();
         transformer.setOutputProperty(OutputKeys.METHOD, "xml");
         transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
         transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"-//W3C//DTD SVG 1.0//EN");
         transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd");
         transformer.transform(new DOMSource(doc), new StreamResult(out));
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
         transformer.transform(new DOMSource(doc), new StreamResult(bos));
         out.flush();
         out.close();
         //将svg直接转为jpg
         /*JPEGTranscoder it = new JPEGTranscoder();
         ByteArrayOutputStream jpg = new ByteArrayOutputStream();
         it.transcode(new TranscoderInput(new ByteArrayInputStream(bos.toByteArray())), new TranscoderOutput(jpg));
         String jpgFile=dest.replaceAll("svg","jpg");
         FileOutputStream jpgOut=new FileOutputStream(jpgFile);
         jpgOut.write(jpg.toByteArray());
         jpgOut.flush();*/
    }
}


SvgToImg
/**
 * @author LiJie
 * 将svg转换为jpg,png格式的
 * 
 * 
 */
public class SvgToImg {
    public void convert2JPEG(String file) throws TranscoderException, IOException {
        /*InputStream in = new FileInputStream(file);
        JPEGTranscoder transcoder = new JPEGTranscoder();
        transcoder.addTranscodingHint(JPEGTranscoder.KEY_XML_PARSER_CLASSNAME,
                 "org.apache.crimson.parser.XMLReaderImpl");
        transcoder.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,new Float(1.0));
        TranscoderInput input = new TranscoderInput(in);
        OutputStream ostream = new FileOutputStream(file.substring(0,file.lastIndexOf("."))+".jpg");
        TranscoderOutput output = new TranscoderOutput(ostream);
        transcoder.transcode(input, output);
        ostream.close();
        ostream.flush();*/       
        JPEGTranscoder t = new JPEGTranscoder();
        InputStream in = new FileInputStream(file);
        TranscoderInput input = new TranscoderInput(in);
        FileOutputStream outputStream = new FileOutputStream(new File(
                file.substring(0,file.lastIndexOf("."))+".jpg"));
        TranscoderOutput output = new TranscoderOutput(outputStream);
        t.transcode(input, output);
        outputStream.flush();
        outputStream.close();
        
    }
/*    public void convert2GIF(String file) throws TranscoderException, IOException{
        GIFTranscoder t = new GIFTranscoder();
        TranscoderInput input = new TranscoderInput(new FileInputStream(file));
        OutputStream ostream = new FileOutputStream(file.substring(0,file.lastIndexOf("."))+".gif");
        TranscoderOutput output = new TranscoderOutput(ostream);
        t.transcode(input, output);
        ostream.flush();
        ostream.close();
    }*/
    public void convert2PNG(String file) {
        try {
            PNGTranscoder t = new PNGTranscoder();
            InputStream in = new FileInputStream(file);
            TranscoderInput input = new TranscoderInput(in);
            FileOutputStream outputStream = new FileOutputStream(new File(
                    file.substring(0,file.lastIndexOf("."))+".png"));
            TranscoderOutput output = new TranscoderOutput(outputStream);
            t.transcode(input, output);
            outputStream.flush();
            outputStream.close();

         } catch (Exception ex) {
             ex.printStackTrace();
         }
    }
    
    /**
     * 将svg字符串转换为png
     * 
     * @param svgCode svg代码
     * @param pngFilePath 保存的路径
     * @throws TranscoderException svg代码异常
     * @throws IOException io错误
     */
    public static void convertToPng(String svgCode, String pngFilePath) throws IOException,
            TranscoderException {

        File file = new File(pngFilePath);

        FileOutputStream outputStream = null;
        try {
            file.createNewFile();
            outputStream = new FileOutputStream(file);
            convertToPng(svgCode, outputStream);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将svgCode转换成png文件,直接输出到流中
     * 
     * @param svgCode svg代码
     * @param outputStream 输出流
     * @throws TranscoderException 异常
     * @throws IOException io异常
     */
    public static void convertToPng(String svgCode, OutputStream outputStream)
            throws TranscoderException, IOException {
        try {
            byte[] bytes = svgCode.getBytes("utf-8");
            PNGTranscoder t = new PNGTranscoder();
            TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(bytes));
            TranscoderOutput output = new TranscoderOutput(outputStream);
            t.transcode(input, output);
            outputStream.flush();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static void main(String[] args) {
    	try {
			convertToPng("D:\\input.svg", "D:\\output.png");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TranscoderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    

猜你喜欢

转载自erhuo.iteye.com/blog/2236646
EMF