When converting from SVG to PNG with Apache Batik I sometimes get strange errors. For example for this SVG https://www.macstories.net/app/themes/macstories4/images/logo-shape-bw.svg it throws an exception, but not for this https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg
Here is my code:
package com.stackoverflow.batik;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.batik.transcoder.SVGAbstractTranscoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
public class Converter {
public static BufferedImage convertSVGToPNG(String url) throws TranscoderException, IOException {
ByteArrayOutputStream resultByteStream = new ByteArrayOutputStream();
TranscoderInput transcoderInput = new TranscoderInput(url);
TranscoderOutput transcoderOutput = new TranscoderOutput(resultByteStream);
PNGTranscoder pngTranscoder = new PNGTranscoder();
pngTranscoder.addTranscodingHint(SVGAbstractTranscoder.KEY_HEIGHT, 256f);
pngTranscoder.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, 256f);
pngTranscoder.transcode(transcoderInput, transcoderOutput);
resultByteStream.flush();
return ImageIO.read(new ByteArrayInputStream(resultByteStream.toByteArray()));
}
public static void main(String args[]) throws TranscoderException, IOException {
BufferedImage image = convertSVGToPNG("https://www.macstories.net/app/themes/macstories4/images/logo-shape-bw.svg");
assert image.getWidth() == 256;
assert image.getHeight() == 256;
}
}
And this is the exception
Exception in thread "main" org.apache.batik.transcoder.TranscoderException: null
Enclosed Exception:
The current document is unable to create an element of the requested type (namespace: http://www.w3.org/2000/svg, name: description).
at org.apache.batik.transcoder.XMLAbstractTranscoder.transcode(Unknown Source)
at org.apache.batik.transcoder.SVGAbstractTranscoder.transcode(Unknown Source)
at com.stackoverflow.batik.Converter.convertSVGToPNG(Converter.java:25)
at com.stackoverflow.batik.Converter.main(Converter.java:33)
Am I doing something wrong?
SVG has no description tag. I assume you meant to write <desc>
which does exist.
Chrome and other browsers ignore unknown tags. Batik should too, but does not. You could always replace the description tag by a desc tag using an XSLT transform (or some other mechanism) prior to giving it to Batik.