Simply put, I'm looking for a way to make an ImageIcon from an SVG file using the batik library. I don't want to have to raster the SVG to disk first, I just want to be able to pull an svg out of the jar file and have it land as a UI element.
I feel like this should be reasonably easy, but the batik javadocs aren't telling me what I need to know.
(Why batik? Well, we're already using it, so we don't have to run another library past legal.)
I have just followed Devon's approach with Batik-1.7
However, in order to make it work I had to make the following additions to the hints object:
Seems like something has been updated in batik's XMLAbstractTranscoder( http://svn.apache.org/repos/asf/xmlgraphics/batik/tags/batik-1_7/sources/org/apache/batik/transcoder/XMLAbstractTranscoder.java) with version 1.7.
If ever you no longer wish to include the dependency on Batik in your application you can transform a SVG file directly into Java2D with the Flamingo SVG Transcoder:
http://ebourg.github.com/flamingo-svg-transcoder
It generates icon classes roughly equivalent in size to a compressed SVG file. The code generated has no external dependency.
I tried using Devon's and John's suggestions, which nearly worked for me. I had to make some tweaks as follows, feel free to use:
To avoid passing dom parameters :
transcoder.setTranscodingHints((Map<?, ?>) hints);
It's really quite easy, just not very intuitive.
You need to extend
ImageTranscoder
. In thecreateImage
method you allocate aBufferedImage
, cache it as a member variable, and return it. ThewriteImage
method is empty. And you'll need to add a getter to retrieve theBufferedImage
.It will look something like this:
Now, to create an image you create an instance of your transcoder and pass it the desired width and height by setting
TranscodingHints
. Finally you transcode from a TranscoderInput to a null target. Then call the getter on your transcoder to obtain the image.The call looks something like this:
Simple, right? (Yeah, right. Only took me 2 weeks to figure that out. Sigh.)