我正在使用Java FX,我想将节点转换为图像。我找到了这个资源,但它并没有解决我的问题,因为我想将节点转换为图像,而不是整个场景。
How to output the content of a Scene graph in JavaFx 2.0 to an Image
答案 0 :(得分:13)
您可以使用新的FX 2.2快照功能:
public class TrySnapshot extends Application {
@Override
public void start(Stage primaryStage) {
final VBox vbox = new VBox(2);
final Button btn = new Button();
vbox.getChildren().add(btn);
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
// here we make image from vbox and add it to scene, can be repeated :)
WritableImage snapshot = vbox.snapshot(new SnapshotParameters(), null);
vbox.getChildren().add(new ImageView(snapshot));
System.out.println(vbox.getChildren().size());
}
});
Scene scene = new Scene(new Group(vbox), 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
如果您出于某种原因必须使用较旧的FX,只需使用您链接的代码示例中的Node#getBoundsInParent
调用将场景坐标更改为您的节点坐标。
答案 1 :(得分:7)
这是我的问题的解决方案。这个解决方案是Sergey和jewelsea的帮助。此解决方案位于javafx 2.2中。谢谢Sergey和jewelsea。
public class TrySnapshot extends Application {
javafx.embed.swing.SwingFXUtils fXUtils;
BufferedImage bufferedImage = new BufferedImage(550, 400, BufferedImage.TYPE_INT_ARGB);
File file = new File("C:/Users/PC1/Desktop/Sample Images/test.jpg");
VBox vbox = null;
@Override
public void start(Stage primaryStage) {
vbox = new VBox();
Button btn = new Button();
Image i = new Image("file:C:\\Koala.jpg");
ImageView imageView = new ImageView();
imageView.setImage(i);
vbox.getChildren().add(imageView);
vbox.setSpacing(10);
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
// here we make image from vbox and add it to scene, can be repeated :)
WritableImage snapshot = vbox.snapshot(new SnapshotParameters(), null);
vbox.getChildren().add(new ImageView(snapshot));
saveImage(snapshot);
System.out.println(vbox.getChildren().size());
}
});
Scene scene = new Scene(new Group(btn), 500, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
private void saveImage(WritableImage snapshot) {
BufferedImage image;
image = javafx.embed.swing.SwingFXUtils.fromFXImage(snapshot, bufferedImage);
try {
Graphics2D gd = (Graphics2D) image.getGraphics();
gd.translate(vbox.getWidth(), vbox.getHeight());
ImageIO.write(image, "png", file);
} catch (IOException ex) {
Logger.getLogger(TrySnapshot.class.getName()).log(Level.SEVERE, null, ex);
};
}
}
答案 2 :(得分:0)
我有一个类似的问题,我想将一个节点转换为图像。
这个完美适合我:
Image image = ((ImageView) node).getImage();