Skip to content

Instantly share code, notes, and snippets.

@eclecticlogic
Created December 10, 2013 13:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eclecticlogic/7890297 to your computer and use it in GitHub Desktop.
Save eclecticlogic/7890297 to your computer and use it in GitHub Desktop.
Java code to convert an SVG into a BufferedImage (PNG, JPEG etc.) using Apache Batik
public BufferedImage createImageFromSVG(String svg) {
Reader reader = new BufferedReader(new StringReader(svg));
TranscoderInput svgImage = new TranscoderInput(reader);
BufferedImageTranscoder transcoder = new BufferedImageTranscoder();
transcoder.addTranscodingHint(PNGTranscoder.KEY_WIDTH, (float) component.getWidth());
transcoder.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, (float) component.getHeight());
try {
transcoder.transcode(svgImage, null);
} catch (TranscoderException e) {
throw Throwables.propagate(e);
}
return transcoder.getImage();
}
@ripper2hl
Copy link

What version of apache batik are using?, I can not find the class BufferedImageTranscoder

@saifolanwar
Copy link

while I'm using your BufferedImageTranscoder, I encountered this problem; The element type "link" must be terminated by the matching end-tag ""

@nupur-agarwal
Copy link

nupur-agarwal commented Jan 14, 2018

You can also convert svg to png format without the use of Batik Transcoder. Follow below link:
https://nupur28ag.blogspot.in/

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

@juan-angel
Copy link

You can also convert svg to png format without the use of Batik Transcoder. Follow below link:

Nop. It doesn't work. ImageIO#read does not support SVG format.
You can find the supported formats following this link https://docs.oracle.com/javase/tutorial/2d/images/loadimage.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment