i Devote
i Devote

Reputation: 3

Save Snapshot of pane to different sizes to file

Is there a way to save the snapshot image to different sizes to the disk apart from the original size of the pane_scene. I've tried everything I found on the web including setting the parameters for the new Snapshot but I get an error. How do I alter the code below to save the snapshot image in 1080 * 1080 pixels? Thank you very much

public class Controller {
@FXML
private Pane pane_scene;
@FXML
private ImageView img;

    public void download()throws IOException {
        if (img.getImage() == null){
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Note");
            alert.setHeaderText("Information");
            alert.setContentText("Please preview image first");
            alert.show();
        }
        else {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("Save");
            fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("png", "*.png"));
            File file = fileChooser.showSaveDialog(new Stage());
            if (file != null){
                SnapshotParameters sp = new SnapshotParameters();
                WritableImage image = pane_scene.snapshot(sp,null);
                ImageIO.write(SwingFXUtils.fromFXImage(image,null), "png",file);
                System.out.println(file.getName());
            }
        }
    }
}

Thanks

Upvotes: 0

Views: 147

Answers (1)

mipa
mipa

Reputation: 10650

I am not exactly sure what you want to achieve but I am using the following technique to create render scale aware snapshots and I think that you can do something similar in your case. The trick is to provide an image of the right size and set an explicit transform.

public static WritableImage renderScaleAwareSnapshot(Node node, double renderScale, WritableImage writableImage,
        double x, double y, double width, double height) {
    int renderWidth = (int) Math.rint(renderScale * width);
    int renderHeight = (int) Math.rint(renderScale * height);
    if (writableImage == null || (int) Math.rint(writableImage.getWidth()) != renderWidth
            || (int) Math.rint(writableImage.getHeight()) != renderHeight) {
        writableImage = new WritableImage(renderWidth, renderHeight);
    }
    SnapshotParameters spa = new SnapshotParameters();
    spa.setViewport(new Rectangle2D(x * renderScale, y * renderScale, width, height));
    spa.setTransform(Transform.scale(renderScale, renderScale));
    return node.snapshot(spa, writableImage);
}

Upvotes: 3

Related Questions