Dinesh Pathak DK
Dinesh Pathak DK

Reputation: 305

Convert svg image to png in java by servlet

Here, I am trying to send a SVG image to local server and in output I want to download that image in PNG / JPEG format.

While I have found some solutions but those are done by BATIK libraries, but in my Eclipse BATIK libraries are not supported , so I can't use the batik libraries.

Upvotes: 3

Views: 25319

Answers (3)

Massimo Perin
Massimo Perin

Reputation: 1

To use ImageIO you have to add this library, it adds the support for many image formats SVG included.

https://haraldk.github.io/TwelveMonkeys/

Upvotes: -1

Nupur Agarwal
Nupur Agarwal

Reputation: 9

You can also convert svg to png format without the use of Batik Transcoder.

BufferedImage input_image = null; 
input_image = ImageIO.read(new File("Convert_to_PNG.svg")); //read svginto input_image object
File outputfile = new File("imageio_png_output.png"); //create new outputfile object
ImageIO.write(input_image, "PNG", outputfile);

By simply using the ImageIO library. Hope this will help!

Upvotes: -6

techhunter
techhunter

Reputation: 693

Use batik library. Below is the code.

    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();        
        }
}

Hope it will help you.

Refer this: http://thinktibits.blogspot.com/2012/12/Batik-Convert-SVG-PNG-Java-Program-Example.html

Upvotes: 13

Related Questions