我正在使用 Batik 处理 SVG 图像。具体来说,我有一个具有多种形状的场景,我需要能够将每个形状转换为单独的 BufferedImage。为此,我使用以下代码:
SVGDocument document = null;
// Load the document
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
File file = new File(inPath);
try {
document = (SVGDocument) f.createDocument(file.toURL().toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Build the tree and get the document dimensions
UserAgentAdapter userAgentAdapter = new UserAgentAdapter();
BridgeContext bridgeContext = new BridgeContext(userAgentAdapter);
GVTBuilder builder = new GVTBuilder();
GraphicsNode graphicsNode = builder.build(bridgeContext, document);
CanvasGraphicsNode canvasGraphicsNode = (CanvasGraphicsNode)
graphicsNode.getRoot().getChildren().get(0);
if(canvasGraphicsNode.getChildren().get(i) instanceof ShapeNode) {
currentNode = (ShapeNode) canvasGraphicsNode.getChildren().get(i);
convertNodeToImage (currentNode);
}
这是相当标准的。我启动 Batik 并让它解析 SVG 文件。这是将节点转换为图像功能:
Rectangle2D bounds;
BufferedImage bufferedImage;
Graphics2D g2d;
// This is supposed to get the bounds of the svg node. i.e. the rectangle which would
// fit perfectly around the shape
bounds = sn.getSensitiveBounds();
// Transform the shape so it's in the top left hand corner based on the bounds
sn.setTransform(AffineTransform.getTranslateInstance(-bounds.getX(), -bounds.getY()));
// Create a buffered image of the same size as the svg node
bufferedImage = new BufferedImage((int) bounds.getWidth(), (int) bounds.getHeight(),
BufferedImage.TYPE_INT_ARGB);
// Paint the node to the buffered image and convert the buffered image to an input
// stream
g2d = (Graphics2D) bufferedImage.getGraphics();
sn.paint(g2d);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
return is;
这适用于矩形和直线形状,但不适用于样条曲线。对于样条线,边界大于渲染的样条线。我认为这是因为 getBounds 函数在边界计算中包含了控制点。我需要找到样条线的边界,即如果样条线被抚摸,我想找到该笔划的边界。我已经尝试了所有的 getBounds() 函数(getSensativeBounds、getGeometryBounds ...),它们都给了我相同的结果。所以我想知道我是否错过了什么?这是蜡染中的一个错误?或者如果有解决方法?
我想到的一种解决方法是获取形状的顶点列表并手动计算边界。但是,我一直无法找到如何获取轮廓顶点列表。
任何帮助将不胜感激。