SVG 到 PNG - 蜡染

SVG to PNG - Batik

使用 Apache Batik 从 SVG 转换为 PNG 时,有时会出现奇怪的错误。例如对于这个 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

这是我的代码:

package com.Whosebug.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;
    }
}

这是个例外

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.Whosebug.batik.Converter.convertSVGToPNG(Converter.java:25)
        at com.Whosebug.batik.Converter.main(Converter.java:33)

我是不是做错了什么?

SVG 没有描述标签。我假设你打算写 <desc> which does exist.

Chrome 等浏览器忽略未知标签。蜡染也应该,但没有。在将 description 标签提供给 Batik 之前,您始终可以使用 XSLT 转换(或其他某种机制)将 description 标签替换为 desc 标签。