如何使用 batik 获取 SVG 图像的图像大小 (width/height)

How to get the image size (width/height) of an SVG image with batik

如何使用 batik (1.7) 获取 SVG 图像的大小 (width/height)?

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

示例可以直接执行,正在下载打开的图片clipart.org。除了绝对大小之外,我还对图像的纵横比感兴趣。

试试这个代码,顺便说一句,SAXparser 在你传递的 svg 图像的情况下引发错误,因为应该为圆形元素定义属性 r 我在 Batik 附带的 svg 样本上做了我的睾丸 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(): Returns 此节点的原始绘制所覆盖区域的边界。这是填充和描边的绘制区域,但不考虑剪裁、遮罩或过滤

a course explaining batik(useful)

要获取 SVG 图像尺寸和比例,检查 SVG 图像的 viewBox 属性也足够了。

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);

String viewBox = document.getDocumentElement().getAttribute("viewBox");
String[] viewBoxValues = viewBox.split(" ");
if (viewBoxValues.length > 3) {
    width = Integer.parseInt(viewBoxValues[2]);
    height = Integer.parseInt(viewBoxValues[3]);
}

在这段代码中,我们检查 viewBox 属性,如果它存在并且有 4 个值,我们取第 3 个(宽度)和第 4 个(高度)。