【问题标题】:Convert SVG include external CSS to image java将 SVG 包括外部 CSS 转换为图像 java
【发布时间】:2018-02-09 23:31:04
【问题描述】:

我想将 SVG 文件转换为图像。问题是我的 SVG 使用外部 CSS 文件,当我使用 Apache Batik 时,它无法识别外部 CSS 文件,它只显示内联 SVG 标签的样式。这是我的示例代码:

public static void svg2jpgBatik1() {
        JPEGTranscoder transcoder = new JPEGTranscoder();

        try {

            // Create a JPEG transcoder
            JPEGTranscoder t = new JPEGTranscoder();
            // Set the transcoding hints.
            t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,
                    0.8f);

            // Create the transcoder input.
            String svgURI = new File("D:\\SVG_PATH\\map.svg").toURL().toString();
            TranscoderInput input = new TranscoderInput(svgURI);

            // Create the transcoder output.
            OutputStream ostream = new FileOutputStream("D:\\JPEG_PATH\\map.jpg");
            TranscoderOutput output = new TranscoderOutput(ostream);
            t.addTranscodingHint(JPEGTranscoder.KEY_ALTERNATE_STYLESHEET, "D:\\STYLESHEET_PATH\\style.css");
            t.addTranscodingHint(JPEGTranscoder.KEY_BACKGROUND_COLOR, Color.blue);

            // Save the image.
            t.transcode(input, output);

            // Flush and close the stream.
            ostream.flush();
            ostream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }

这条线有效:

t.addTranscodingHint(JPEGTranscoder.KEY_BACKGROUND_COLOR, Color.blue);

虽然这条线不起作用:

 t.addTranscodingHint(JPEGTranscoder.KEY_ALTERNATE_STYLESHEET, "D:\\STYLESHEET_PATH\\style.css");

在 SVG 中我添加了这部分:

<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 10 1000" preserveAspectRatio="xMinYMin meet"> 
<defs>
    <link href="STYLESHEET_PATH\\style.css" type="text/css" rel="stylesheet" 
          xmlns="http://www.w3.org/1999/xhtml"/>

  </defs>

当我在浏览器中打开它时应用了 SVG,但在蜡染中它不适用。

我也把样式放到了SVG中的tag里面,结果还是一样。

它可以应用的唯一样式是内联 SVG 样式,例如 fill="#FFFFFF"

<text text-anchor="middle" alignment-baseline="middle"  x="624" xml:space="preserve" y="123.0" 
       fill="#FFFFFF"  >Sample Text</text>

我想知道是否有人可以帮助我解决这个问题,或者让我知道当我将其转换为图像时,从 外部 CSS 获得 SVG 样式的任何最佳替代方案。

提前致谢。

【问题讨论】:

  • 感谢@RobertLongson 的提示。我找到了解决方案。

标签: java css svg jpeg batik


【解决方案1】:

我在 SVG 代码的顶部添加了这一行:

<?xml-stylesheet type="text/css" href="style.css" ?>

而不是SVG标签后面的这部分:

<defs>
    <link href="style.css" type="text/css" rel="stylesheet" 
          xmlns="http://www.w3.org/1999/xhtml"/>

  </defs>

现在它使用来自外部 CSS 文件的样式制作图像。

所以 SVG 文件是:

<?xml-stylesheet type="text/css" href="style.css" ?>
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 10 1000" preserveAspectRatio="xMinYMin meet"> 

【讨论】:

    猜你喜欢
    • 2014-05-25
    • 1970-01-01
    • 2016-04-27
    • 2021-04-24
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多