Convert SVG to PNG Java Example

Apache Batik – SVG to PNG Conversion


In this example, we will explain how to convert a SVG Image to PNG, in Java, by using Apache Batik library. We will provide a Java Program to do this transcoding, and provide the output of the code to check the conversion. This example is on the same lines as of our earlier tutorial on SVG to JPEG transformation.

Input SVG File


We will use the same SVG file that we used in the SVG to JPEG tutorial. You may wish to take a copy of the file from the previous post, or you can alternatively, use your own SVG Image for the example. We will now provide the step by step guide for this conversion.

Read SVG Image to TranscoderInput


This is the first step in the program and in this we use Java NIO (you can still use java.io.File if you are running a older version of Java) to accept the file in TranscoderInput object. The code fragment is provided below:
        //Step -1: We read the input SVG document into Transcoder Input
        //We use Java NIO for this purpose
        String svg_URI_input = Paths.get("chessboard.svg").toUri().toURL().toString();
        TranscoderInput input_svg_image = new TranscoderInput(svg_URI_input);        

Set Output PNG Image


In this step, we create TranscoderOutput object, that maps to the output PNG image. We will create an OutputStream object and pass this to TranscoderOutput constructor.This sets the output definition right and we can then use PNGTranscoder to set the output PNG image properties.


        //Step-2: Define OutputStream to PNG Image and attach to TranscoderOutput
        OutputStream png_ostream = new FileOutputStream("chessboard.png");
        TranscoderOutput output_png_image = new TranscoderOutput(png_ostream);              

Create PNG Transcoder


We create a blank PNG Transcoder object which will do the conversion for us. For this tutorial, we are not going to set any properties against the PNG file. But you can specify properties that include Gamma correction key as an example.


        // Step-3: Create PNGTranscoder and define hints if required
        PNGTranscoder my_converter = new PNGTranscoder();        

Convert SVG to PNG


In this step, we invoke the “transcode” method in PNGTranscoder class and pass the input and output objects created earlier. This step converts SVG Image to PNG Image file and generates the output file.


        // Step-4: Convert and Write output
        my_converter.transcode(input_svg_image, output_png_image);

At the end of the step, you can close the flush the outputstream.

Batik – SVG to PNG – Complete Java Program


The complete Java program that converts SVG Image to PNG using Apache Batik is provided below:


import java.io.*;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import java.nio.file.Paths;
import java.nio.file.Path;
public class svg2png {
    public static void main(String[] args) throws Exception {
        //Step -1: We read the input SVG document into Transcoder Input
        //We use Java NIO for this purpose
        String svg_URI_input = Paths.get("chessboard.svg").toUri().toURL().toString();
        TranscoderInput input_svg_image = new TranscoderInput(svg_URI_input);        
        //Step-2: Define OutputStream to PNG Image and attach to TranscoderOutput
        OutputStream png_ostream = new FileOutputStream("chessboard.png");
        TranscoderOutput output_png_image = new TranscoderOutput(png_ostream);              
        // Step-3: Create PNGTranscoder and define hints if required
        PNGTranscoder my_converter = new PNGTranscoder();        
        // Step-4: Convert and Write output
        my_converter.transcode(input_svg_image, output_png_image);
        // Step 5- close / flush Output Stream
        png_ostream.flush();
        png_ostream.close();        
    }
}

To compile this program you need batik-transcoder.jar file. To run the program, you need quite a number of Batik JAR files. A sample command line is given below:

java  -classpath .;batik-transcoder.jar;batik-dom.jar;batik-bridge
.jar;batik-css.jar;batik-gvt.jar;batik-util.jar;batik-svg-dom.jar;xml-apis-ext.j
ar;xml-apis.jar;batik-ext.jar;batik-xml.jar;batik-anim.jar;batik-parser.jar;bati
k-script.jar;batik-awt-util.jar;batik-codec.jar svg2png

The program generates the output PNG images successfully upon execution. That completes a quick tutorial to convert SVG to PNG in Java, using Batik library. Post your comment / exception if any, and we will have a look.

9 comments:

  1. Hi,
    I ran the exact same code as given by you, and ended up in the following error.

    java.lang.NullPointerException
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at org.xml.sax.helpers.NewInstance.newInstance(NewInstance.java:49)
    at org.xml.sax.helpers.XMLReaderFactory.loadClass(XMLReaderFactory.java:187)
    at org.xml.sax.helpers.XMLReaderFactory.createXMLReader(XMLReaderFactory.java:180)
    at org.apache.batik.dom.util.SAXDocumentFactory.createDocument(Unknown Source)
    at org.apache.batik.dom.util.SAXDocumentFactory.createDocument(Unknown Source)
    at org.apache.batik.dom.svg.SAXSVGDocumentFactory.createDocument(SAXSVGDocumentFactory.java:200)
    at org.apache.batik.dom.svg.SAXSVGDocumentFactory.createDocument(SAXSVGDocumentFactory.java:281)
    at org.apache.batik.transcoder.XMLAbstractTranscoder.transcode(Unknown Source)
    at org.apache.batik.transcoder.SVGAbstractTranscoder.transcode(Unknown Source)
    at SVGToPNGExample.main(SVGToPNGExample.java:40)

    Debugging more, i found out that the parserclass name is going as null and hence causing the loading error.

    Below are the jars i use:
    batik-dom-1.6-1.jar
    batik-css-1.6-1.jar
    batik-bridge-1.7.jar
    batik-gvt-1.7.jar
    batik-util-1.7.jar
    batik-svg-dom-1.7.jar
    batik-anim-1.7.jar
    batik-codec-1.7.jar
    batik-parser-1.7.jar
    batik-script-1.7.jar
    batik-xml-1.7.jar
    xml-apis-2.0.2.jar
    xml-apis-ext-1.3.04.jar
    batik-awt-util-1.7.jar
    batik-transcoder-1.7.jar


    Please help!

    ReplyDelete
  2. Hi.
    You need to these jars.
    xalan-2.6.0.jar
    xerces_2_5_0.jar
    xml-apis.jar
    xml-apis-ext.jar

    I hope this your help.

    ReplyDelete
  3. Thank you very much! :)

    ReplyDelete
  4. I added all these jars to my Java project and ran the same code. I didn't get any error but the png output was not generated :/

    ReplyDelete
    Replies
    1. Same for me )=
      No errors in log, no image

      Delete
    2. Some days ago fixed it.
      Code is fine, but pay attention to streams closing - I work within servlet and there were some errors there.
      Now works fine

      Delete
  5. Hi All,
    any one share sample code with complete jars. I am getting different error of differ images. Please it is urgent

    ReplyDelete
  6. hai sir,
    how to print hand written math expression using svg image

    ReplyDelete
  7. this is not working in eclipse .
    it generate the following errors:

    [ERROR] Errors in 'file:/E:/JAVA%20Programs/ImageConverter/src/com/imageConverter/client/ImageConverter.java'
    [ERROR] Line 45: No source code is available for type org.apache.batik.transcoder.TranscoderException; did you forget to inherit a required module?
    [ERROR] Line 27: No source code is available for type org.apache.batik.transcoder.TranscoderInput; did you forget to inherit a required module?
    [ERROR] Line 32: No source code is available for type org.apache.batik.transcoder.image.PNGTranscoder; did you forget to inherit a required module?
    [ERROR] Line 42: No source code is available for type java.io.FileNotFoundException; did you forget to inherit a required module?
    [ERROR] Line 29: No source code is available for type java.io.FileOutputStream; did you forget to inherit a required module?
    [ERROR] Line 25: No source code is available for type java.nio.file.Paths; did you forget to inherit a required module?
    [ERROR] Line 30: No source code is available for type org.apache.batik.transcoder.TranscoderOutput; did you forget to inherit a required module?
    [ERROR] Line 39: No source code is available for type java.net.MalformedURLException; did you forget to inherit a required module?
    [ERROR] Hint: Check the inheritance chain from your module; it may not be inheriting a required module or a module may not be adding its source path entries properly

    >>and i have already imported these classes

    ReplyDelete