如何使用蜡染获取SVG图像的图像大小(宽度/高度)

时间:2016-02-02 19:38:53

标签: java image svg batik

如何使用蜡染(1.7)获取SVG图像的大小(宽度/高度)?

String s = "https://openclipart.org/download/228858";
InputStream is = new URL(s).openStream();

DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = f.newDocumentBuilder();
Document doc = builder.parse(is);

SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(doc);
SVGGraphics2D svg = new SVGGraphics2D(ctx,false);

Dimension d = svg.getSVGCanvasSize();
Rectangle r = svg.getClipBounds();

System.out.println(svg.toString()); //org.apache.batik.svggen.SVGGraphics2D[font=java.awt.Font[family=Dialog,name=sanserif,style=plain,size=12],color=java.awt.Color[r=0,g=0,b=0]]
System.out.println("Dimension null? "+(d==null)); //true
System.out.println("Rectangle null? "+(r==null)); //true

该示例可以直接执行,并从open clipart.org下载图像。作为绝对尺寸的替代,我也对图像的纵横比感兴趣。

1 个答案:

答案 0 :(得分:5)

尝试此代码,顺便说一下SAXparser在您传递的svg图像的情况下引发错误,因为属性r应该为圆形元素定义我在svg样本上制作了我的睾丸与Batik Batik's samples folder一起

SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(
                XMLResourceDescriptor.getXMLParserClassName());

        File file = new File("C:/resources/chessboard.svg");
        InputStream is = new FileInputStream(file);

        Document document = factory.createDocument(
                file.toURI().toURL().toString(), is);
        UserAgent agent = new UserAgentAdapter();
        DocumentLoader loader= new DocumentLoader(agent);
        BridgeContext context = new BridgeContext(agent, loader);
        context.setDynamic(true);
        GVTBuilder builder= new GVTBuilder();
        GraphicsNode root= builder.build(context, document);

        System.out.println(root.getPrimitiveBounds().getWidth());
        System.out.println(root.getPrimitiveBounds().getHeight());

<强> getPrimitiveBounds(): 返回此节点的原始绘制所覆盖区域的边界。这是填充和描边的绘制区域,但不考虑剪裁,遮罩或过滤

a course explaining batik(useful)