2016-04-26 122 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