javafx snapshot without showing application or Scene

你离开我真会死。 提交于 2020-01-01 11:48:36

问题


Hi i'm using JavaFx WebView to create Screenshot of HTML pages and it works fine but i wanted to know is it possible to do this without launching the application in Graphical Windows!! I mean aren't there any more lightweight method to get the screenshot then this:

public class WebViewSample extends Application {
    private Scene scene;

    @Override
    public void start(Stage stage) {
        // create scene
        scene = new Scene(new Browser(snapshot), 750, 500, Color.web("#666970"));

        stage.setScene(scene);
//        show stage
        stage.show();
    }
    WritableImage snapshot;
    public static void main(String[] args) {
        launch(args);
        System.err.println("launched!");
    }
}
class Browser extends Region {


    final ImageView selectedImage = new ImageView();
    final WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();
    private final  WritableImage snapshotImage;

    public Browser(WritableImage snapshot) {
        this.snapshotImage= snapshot;
        // process page loading
        webEngine.getLoadWorker().stateProperty().addListener(
                new ChangeListener<State>() {
                    @Override
                    public void changed(ObservableValue<? extends State> ov,
                                        State oldState, State newState) {
                        if (newState == State.SUCCEEDED) {
                            WritableImage newSnapshot = browser.snapshot(null, snapshotImage);
                            File file = new File("test2.png");
                            RenderedImage renderedImage = SwingFXUtils.fromFXImage(newSnapshot, null);
                            try {
                                ImageIO.write(renderedImage, "png", file);
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                            System.exit(0);
                        }
                    }
                }
        );

        // load the home page        
        webEngine.load("http://localhost/");


        //add components
        getChildren().add(browser);
    }



}  

回答1:


For JavaFX 2.2 and below, there's not functionality of the kind.

Headless JavaFX applications are currently not possible, and a main JavaFX thread is mandatory.

The best you can do is read upon several workarounds for achieving this.

Related StackOverflow questions:

  • JavaFX for server-side image generation
  • Generating image at server side using Java FX
  • JavaFx in headless mode
  • How to test JavaFX 2 in a headless environment?

    来源:https://stackoverflow.com/questions/22730227/javafx-snapshot-without-showing-application-or-scene

  • 易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!