I have a utility method which takes an SVG and uses Apache Batik to rasterize it:
public static BufferedImage rasterize(InputStream svgInput, int width, int height) throws TranscoderException {
AtomicReference<BufferedImage> results = new AtomicReference<BufferedImage>();
ImageTranscoder transcoder = new ImageTranscoder() {
@Override
public BufferedImage createImage(int width, int height) {
return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
@Override
public void writeImage(BufferedImage image, TranscoderOutput output) throws TranscoderException {
results.set(image);
}
};
TranscodingHints hints = new TranscodingHints();
if (width > 0)
hints.put(SVGAbstractTranscoder.KEY_WIDTH, (float) width);
if (height > 0)
hints.put(SVGAbstractTranscoder.KEY_HEIGHT, (float) height);
hints.put(XMLAbstractTranscoder.KEY_DOM_IMPLEMENTATION, SVGDOMImplementation.getDOMImplementation());
hints.put(XMLAbstractTranscoder.KEY_DOCUMENT_ELEMENT_NAMESPACE_URI, SVGConstants.SVG_NAMESPACE_URI);
hints.put(XMLAbstractTranscoder.KEY_DOCUMENT_ELEMENT_NAMESPACE_URI, SVGConstants.SVG_NAMESPACE_URI);
hints.put(XMLAbstractTranscoder.KEY_DOCUMENT_ELEMENT, SVGConstants.SVG_SVG_TAG);
hints.put(XMLAbstractTranscoder.KEY_XML_PARSER_VALIDATING, false);
transcoder.setTranscodingHints(hints);
transcoder.transcode(new TranscoderInput(svgInput), null);
return results.get();
}
This is one of the vector graphics that I am using:
<svg xmlns="; fill="currentColor" class="bi bi-clock" viewBox="0 0 16 16">
<path d="M8 3.5a.5.5 0 0 0-1 0V9a.5.5 0 0 0 .252.434l3.5 2a.5.5 0 0 0 .496-.868L8 8.71z" />
<path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m7-8A7 7 0 1 1 1 8a7 7 0 0 1 14 0" />
</svg>
As you can see, the fill
attribute is set to currentColor
. This always results in a black fill. Is there a way to specify a value for currentColor
through Batik so the resulting image is not black?