2010-03-03 100 views
5

我正在嘗試生成SVG圖像,然後使用Apache Batik將其轉碼爲PNG。但是,我最終得到一個空的圖像,我不明白爲什麼。將SVG轉碼爲PNG時獲取空圖像

我使用SVGDomImplementation中的Document作爲轉碼的基礎(避免將SVG寫入磁盤並重新加載)。這裏有一個例子:

DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation(); 
    String namespace = SVGDOMImplementation.SVG_NAMESPACE_URI; 
    Document document = domImpl.createDocument(namespace, "svg", null); 

    //stuff that builds SVG (and works) 

    TranscoderInput transcoderInput = new TranscoderInput(svgGenerator.getDOMFactory()); 
    PNGTranscoder transcoder = new PNGTranscoder(); 
    transcoder.addTranscodingHint(PNGTranscoder.KEY_WIDTH, new Float(svgWidth)); 
    transcoder.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, new Float(svgHeight)); 

    try { 
    File temp = File.createTempFile(key, ".png"); 
    FileOutputStream outputstream = new FileOutputStream(temp); 

    TranscoderOutput output = new TranscoderOutput(outputstream); 

    transcoder.transcode(transcoderInput, output); 
    outputstream.flush(); 
    outputstream.close(); 
    name = temp.getName(); 
    } catch (IOException ioex) { 
    ioex.printStackTrace(); 
    } catch (TranscoderException trex) { 
    trex.printStackTrace(); 
    } 

我的問題是,生成的圖像是空的,我看不出爲什麼。任何提示?

回答

1

我認爲這取決於您如何創建SVG文檔。你用什麼svgGenerator(我認爲是SVGGraphics2D)?

TranscoderInput transcoderInput = new TranscoderInput(svgGenerator.getDOMFactory()); 

如果你在document建立了SVG文件,那麼你應該把它傳遞給TranscoderInput構造。

This page有一個將SVG DOM柵格化爲JPEG的例子。

+0

正確,svgGenerator是一個SVGGraphics2D。 getDOMFactory()返回與我在方法開頭創建的文檔/對象相同的文檔/對象,因此它沒有區別。 我已經多次瀏覽了JPEG示例。也許僅僅把這個例子改爲PNG是不夠的(我沒有真正測試過這個特定的例子),也許PNG代碼轉換器需要一些其他的/額外的設置,我沒有看到。 我以另一種方式解決了我的實際問題(正確地將SVG轉換爲PDF),因此這不再需要。 – fiskeben 2010-03-08 08:58:44