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

How can I get the size (width/height) of an SVG image using batik (1.7)?

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

The example can be directly executed and is downloading a image from open clipart.org. Alternatively to a absolute size I'm also interested in the aspect ratio of the image.



Solution 1:[1]

To get the SVG image dimensions and ratio it is also sufficient to check viewBox attribute of an SVG image.

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

In this code we check viewBox attribute and if it is present and has 4 values, we take 3rd (width) and 4th (height).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 michal.jakubeczy