【问题标题】:How to get the image size (width/height) of an SVG image with batik如何使用蜡染获得 SVG 图像的图像大小(宽度/高度)
【发布时间】:2016-05-11 18:49:57
【问题描述】:

如何使用 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

该示例可以直接执行,并且正在从打开的clipart.org 下载图像。除了绝对尺寸,我还对图像的纵横比感兴趣。

【问题讨论】:

    标签: java image svg batik


    【解决方案1】:

    试试这段代码,顺便说一句,SAXparser 会在你传递的 svg 图像的情况下引发错误,因为属性 r 应该为圆形元素定义我在 Batik Batik's samples folder 附带的 svg 样本上进行了测试

    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)

    【讨论】:

    • 感谢您提供代码,但如果 SVG 结构完美,这似乎是另一个获取边界的示例,不幸的是,我必须处理这些格式错误的文档。
    • accualy 它不是格式错误的文档,但它为 sodipodi xr: 和 yr: 使用 sodipodi 命名空间,如果它们都具有相同的值,则它们将执行 r 的工作
    • 当我进行这些测量并使用PNGTranscoder.KEY_MAX_WIDTHPNGTranscoder.KEY_MAX_HEIGHT 进行渲染时,我得到的图像比我在不分配这些键的情况下渲染时得到的图像要小得多。是否存在单位不匹配?
    • 当我将宽度高度从 SVG 文档根元素中拉出,然后使用 KEY_MAX_WIDTH 和 KEY_MAX_HEIGHT 进行渲染时,我得到了正确的尺寸。
    猜你喜欢
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 2016-11-04
    • 2011-11-26
    • 2015-08-16
    • 1970-01-01
    相关资源
    最近更新 更多