2016-04-26 126 views
0

我有一个svg图像,我想导出为png。如何解码由window.btoa使用Java编码的base64图像

在客户端使用JavaScript,我转换成的base64

var s = new XMLSerializer().serializeToString(document.getElementById("svg")) 
var encodedData = window.btoa(s); 

在服务器端我想将它解码,并创建一个.png文件

BASE64Decoder decoder = new BASE64Decoder(); 
byte[] imageByte = decoder.decodeBuffer(string); 

但是,这给了我一个文件无法打开。

或者是否有任何其他方式可以将svg导出为png。因为我的SVG包含来自外部源的图像,我不能使用toDataUrl

回答

0

解码的字节数组将SVG格式的。使用一些库(我用阿帕奇蜡染转码器

BASE64Decoder decoder = new BASE64Decoder(); 
    byte[] image = decoder.decodeBuffer(string); 
    String fileLocation = "C:\temp"; 
    String fileName = "New-" + System.currentTimeMillis(); 
    File file = new File(fileLocation +File.separator+ fileName + ".svg"); 
    FileOutputStream fop = new FileOutputStream(file); 
    if (!file.exists()) { 
     file.createNewFile(); 
    } 
    fop.write(image); 
    fop.flush(); 
    fop.close(); 
    PNGTranscoder transcoder = new PNGTranscoder(); 
    TranscoderInput tinput = new TranscoderInput(new FileInputStream(fileLocation + File.separator + fileName +".svg")); 
    OutputStream ostream = new FileOutputStream(fileLocation + File.separator + fileName +".png"); 
    TranscoderOutput toutput = new TranscoderOutput(ostream); 
    try { 
      transcoder.transcode(tinput, toutput); 
    } catch (TranscoderException e) { 
      System.out.println("error*"); 
      e.printStackTrace(); 
    } 
    ostream.close(); 
0

的Java 8拥有基地64编码的支持和解码

可以按如下

byte [] barr = Base64.getDecoder().decode(encoded); 

但是做到这一点,你为什么将它作为基础64编码的字符串传递?为什么不将图像作为多部分/表单数据发送?

+0

对不起,我不知道如何通过SVG作为多/表单数据转换成PNG。它应该转换成PNG然后发送? – Jerry

+0

该文件格式不重要。这个答案包含一些关于如何在java中进行文件上传的说明http://stackoverflow.com/questions/19510656/how-to-upload-files-on-server-folder-using-jsp –

+0

感谢您的回复。我正在使用d3.js绘制svg,我想将它保存为png图像。因为我在svg中使用外部图像源,所以当我尝试使用** toDataUrl **时,出现CORS错误。您提供的参考不会帮助我:( – Jerry

0

对于mime类型解码,利用这一点,

byte[] decodedBuffer = Base64.getMimeDecoder().decode(encodedBuffer); 

资源链接:https://examples.javacodegeeks.com/core-java/util/base64/java-8-base64-encoding-example/

+0

@Jerry请您分享完整的错误日志? – SkyWalker

+0

@Jerry并提供您的问题的完整代码 – SkyWalker

+0

我试过它是解码。但是当我创建一个文件仍然它是未来作为不支持档案\ n'字节[]图像= Base64.getMimeDecoder()进行解码(encodedBuffer); \t \t \t字符串DIR = System.getProperty( “java.io.tmpdir”); \t \t \t String fileName = input.getShortName(); \t \t \t File file = new File(dir + File.separatorChar + fileName); \t FileOutputStream fop = new FileOutputStream(fi LE); \t if(!file.exists()){ \t \t file.createNewFile(); \t} \t fop.write(image); \t fop.flush(); \t fop.close();' – Jerry