Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert SVG into PNG on-the-fly

Tags:

java

png

svg

batik

I try to convert an svg into PNG. the svg document is coming from a server as an Inputstream.

First, I convert the svg stream into byte array with:

 byte[] streamBytes = IOUtils.toByteArray(svgStream);

Then I convert the bytes into OutputStream(PNG) with the following code.

private ByteArrayOutputStream svgToPng(byte[] streamBytes)
                                            throws TranscoderException, IOException {
        PNGTranscoder t = new PNGTranscoder();
        TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(streamBytes));
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        TranscoderOutput output = new TranscoderOutput(ostream);

        t.transcode(input, output);

        ostream.flush();
        // ostream.close();
        return ostream;
    }

But i get null pointer exception by "t.transcode(input, output);"

org.apache.batik.transcoder.TranscoderException: null
Enclosed Exception:
Premature end of file.
graphdata : null
    at org.apache.batik.transcoder.XMLAbstractTranscoder.transcode(XMLAbstractTranscoder.java:136)
    at org.apache.batik.transcoder.SVGAbstractTranscoder.transcode(SVGAbstractTranscoder.java:156)

Note: If i save the svgstream on th disk and use the following transcoderinput with uri constructor, then it works. But in my case i don't want to save on the disk.

TranscoderInput input = new TranscoderInput(new File("c:/a.svg").toURI().toString());
like image 675
Kayser Avatar asked Nov 17 '11 13:11

Kayser


1 Answers

I found the problem.

I checked each time if the svgstream is ok or not. To see if it is ok, I created each time an SVG file with the code in my comment. Logically it consumed the stream. There was no real stream at the end. It caused the Exception. Thanks to all..

like image 136
Kayser Avatar answered Oct 21 '22 21:10

Kayser