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.
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