Java svg转png

项目业务场景中前端合成的文件格式是svg的,但在java中不能像图片那样用IO流读写合成。

转自 https://www.cnblogs.com/chenjy1225/p/9662218.html 

此文中介绍了如何将svg转成png,亲测有效。maven的依赖要使用博主给出的版本,新版本会报各种类缺失的异常。


        
            batik
            batik-svggen
            1.6
        
        
            batik
            batik-awt-util
            1.6
        
        
            batik
            batik-bridge
            1.6
        
        
            batik
            batik-css
            1.6
        
        
            batik
            batik-dom
            1.6
        
        
            batik
            batik-gvt
            1.6
        
        
            batik
            batik-parser
            1.6
        
        
            batik
            batik-script
            1.6
        
        
            batik
            batik-svg-dom
            1.6
        
        
            batik
            batik-transcoder
            1.6
        
        
            batik
            batik-util
            1.6
        
        
            batik
            batik-xml
            1.6
        
        
            xerces
            xercesImpl
            2.5.0
        
        
            xml-apis
            xmlParserAPIs
            2.0.2
        
        
            org.axsl.org.w3c.dom.svg
            svg-dom-java
            1.1
        
        
            xml-apis
            xml-apis
            2.0.0
        
        
            org.w3c.css
            sac
            1.3
        
public static void convertSvg2Png(File svg, File png) throws IOException,TranscoderException   
       {  
             
            InputStream in = new FileInputStream(svg);  
            OutputStream out = new FileOutputStream(png);  
            out = new BufferedOutputStream(out);  
            
            Transcoder transcoder = new PNGTranscoder();  
            try { 
            TranscoderInput input = new TranscoderInput(in);  
                try {  
                    TranscoderOutput output = new TranscoderOutput(out);  
                    transcoder.transcode(input, output);  
                } finally {  
                    out.close();  
                }  
            } finally {  
                in.close();  
            }  
        }  
        

        public static void main(String args[]){
            
             File f=new File("E:/Pinterest_pinterest30.svg");  
             File destFile=new File("E:/Pinterest_pinterest30.png"); 
             
             try {
                 convertSvg2Png(f, destFile);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (TranscoderException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
            
        }

转换效果,原文可见。

你可能感兴趣的:(java)