可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am using Java FX and I would like to convert a node to an image. I found this resource, but it does not solve my problem as I want to convert a node to an image, not a whole scene.
How to output the content of a Scene graph in JavaFx 2.0 to an Image
回答1:
You can use new FX 2.2 snapshot feature:
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(); }
If you must use older FX for some reason just change scene coordinates to your node coordinates using Node#getBoundsInParent
calls in the code sample you linked.
回答2:
This is solution of my problem. This solution is help of Sergey and jewelsea. This solution is in javafx 2.2. Thanks Sergey and 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); }; } }
回答3:
I had a similar problem where i wanted to convert a node, given from a mousevent, to an image.
This one works for me perfectly:
Image image = ((ImageView) node).getImage();