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.
For <svg> , height defines the vertical length for the rendering area of the SVG viewport. Note: Starting with SVG2, height is a Geometry Property meaning this attribute can also be used as a CSS property for <svg> .
Sizing on SVG is pretty arbitrary as it is a vector format, the layout is done with maths and so isn't dependent on the size you specify. However, if the SVG is rendered on the page and then gets resized size it can make a difference at the rendering stage.
Approach: You can simply customize the class of SVG by changing the height and width of the icons or by changing the values of viewBox attributes of SVG. Note: The viewBox attribute defines the position and dimension of an SVG viewport.
try this code , by the way the SAXparser raises an error in case of the svg image that you passed because the attribute r should be defined for circle element i made my testes on svg samples that come with 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(): Returns the bounds of the area covered by this node's primitive paint. This is the painted region of fill and stroke but does not account for clipping, masking or filtering
a course explaining batik(useful)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With