java svg转png图片的方法代码svgToPng

java | 2019-09-13 10:02:39

java svg转png图片的方法代码svgToPng:方法可以直接使用

public static String svgToPng(String fileName){
                try {
                   
                        String svgStr=replaceTxtByStr(fileName+".svg");
                        byte[] bytes = svgStr.getBytes("utf-8");
                                PNGTranscoder pngTranscoder = new PNGTranscoder();
                                
                                TranscoderInput svgInput = new TranscoderInput(new ByteArrayInputStream(bytes));//new TranscoderInput(new File(fileName+".svg").toURI().toString());
                                FileOutputStream pngFos = new FileOutputStream(fileName+".png");
                                
                                TranscoderOutput pngOutput = new TranscoderOutput(pngFos);
                                pngTranscoder.transcode(svgInput, pngOutput);
                                
                                pngFos.flush();
                                pngFos.close();
                                
                
                } catch (IOException e){
                   try {
                                throw new TranscoderException(e);
                        } catch (TranscoderException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                        }
                } catch (TranscoderException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                return fileName+".png";
    }
    
    public static String replaceTxtByStr(String filePath) {
            String resultFileString="";
        try {
                  File myFile=new File(filePath);
              if(!myFile.exists()){ 
                  System.err.println("Can't Find " + filePath);
              }
              StringBuffer  returnString=new StringBuffer();
              InputStream inputStream=new FileInputStream(myFile);
              InputStreamReader isr = new InputStreamReader(inputStream, "utf-8");
              BufferedReader in = new BufferedReader(isr);
              String str=null;
              while ((str = in.readLine()) != null) 
              {
                      returnString.append(str);
              }
              resultFileString=returnString.toString().replaceAll("′", "x").replaceAll("3", ">=").replaceAll("£", "<=");
              in.close();
              isr.close();
              inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultFileString;
    }


登录后即可回复 登录 | 注册
    
关注编程学问公众号