Monday, July 4, 2016

95. Snapshot

We can save an image of a Node (here a StackPane) to a file.


We have to create a WritableImage using node.snapshot() method.


package ex95;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Button;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

public class Ex95 extends Application {
        public static void main(String[] args) {
               Application.launch(args);
        }

        @Override
        public void start(Stage stage) {
            VBox root = new VBox(50);
            StackPane stackPane = new StackPane();
            
            DropShadow dropShadow = new DropShadow();
            dropShadow.setOffsetX(10);
            dropShadow.setOffsetY(6);
            dropShadow.setColor(Color.BLUE);

            Rectangle rect = new Rectangle(200, 200);
            rect.setArcWidth(175);
            rect.setArcHeight(200);
            rect.setFill(Color.LIME);
                                          
            Text text = new Text("   The\nSnapshot");
            text.setFont(Font.font("Georgia", 32));
            text.setLayoutX(150);
            text.setLayoutY(150);
            
            rect.setEffect(dropShadow);
            text.setEffect(dropShadow);
            stackPane.getChildren().addAll(rect, text);
            
            Button button = new Button("Take Snapshot");
            button.setOnAction(e -> takeSnapshot(stackPane));

            root.getChildren().addAll(stackPane, button);
            root.setAlignment(Pos.CENTER);
            
            Scene scene = new Scene(root,300,400);
            stage.setScene(scene);
            stage.setTitle("Example 95. Snapshot");
            stage.show();
        }

        private void takeSnapshot(Node node) {
               SnapshotParameters params = new SnapshotParameters();
               WritableImage image = node.snapshot(params, null);
               BufferedImage buffImage = 
                       SwingFXUtils.fromFXImage(image, null);
               File file = new File("ex95.png");
            try {
                ImageIO.write(buffImage, "png", file);
            } catch (IOException ex) {
            }
        }
}

This is the output:



When the button (Take Snapshot) is clicked, this is the saved image:


No comments:

Post a Comment