保存JavaFX快照时获取黑色图像

保存JavaFX快照时获取黑色图像,java,javafx,save-image,Java,Javafx,Save Image,我设置了一个后台任务,在给定的面板/图表可见后等待几秒钟。这是通过在后台非GUI线程上运行sleep,然后在唤醒时运行 Platform.runLater 创建快照和映像 在保存图像的真正“操作”发生之前,我们可以看到窗口出现: 在渲染图像时,我们有一个任务使其休眠的背景代码。5000毫秒后,后台任务唤醒并启动Platform.runLater将场景/窗格/图表保存到文件中 import java.awt.Graphics2D; import java.awt.image.BufferedI

我设置了一个后台任务,在给定的面板/图表可见后等待几秒钟。这是通过在后台非GUI线程上运行
sleep
,然后在唤醒时运行

Platform.runLater
创建快照和映像

在保存图像的真正“操作”发生之前,我们可以看到窗口出现:

在渲染图像时,我们有一个
任务
使其休眠的背景代码。5000毫秒后,后台任务唤醒并启动
Platform.runLater
将场景/窗格/图表保存到文件中

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;

import javax.imageio.ImageIO;

public class AutoSnapshot extends Application {

    private static String fileName = "c:/temp/image.jpg";
    private static Color backgroundColor = Color.WHITE;

    @Override
    public void start(Stage primaryStage) {

        AnchorPane root = new AnchorPane();

        // dummy chart
        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();
        xAxis.setLabel("Number of Month");
        final LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis);
        lineChart.setTitle("Stock Monitoring, 2010");
        XYChart.Series series = new XYChart.Series();
        series.setName("My portfolio");
        series.getData().add(new XYChart.Data(1, 23));
        series.getData().add(new XYChart.Data(2, 14));
        series.getData().add(new XYChart.Data(3, 15));
        series.getData().add(new XYChart.Data(4, 24));
        lineChart.getData().add(series);

        root.getChildren().add( lineChart);

        Scene scene = new Scene(root, 800, 600, backgroundColor);
        primaryStage.setScene(scene);
        primaryStage.show();

        Duration delay = Duration.seconds(5);
        PauseTransition pt = new PauseTransition(delay);
        pt.setOnFinished(e -> {
            saveSnapshot(lineChart);
        });
        pt.play();

    }

    public static Image createImage(Node node) {

        WritableImage wi;

        SnapshotParameters parameters = new SnapshotParameters();
        parameters.setFill(backgroundColor);

        int imageWidth = (int) node.getBoundsInLocal().getWidth();
        int imageHeight = (int) node.getBoundsInLocal().getHeight();

        wi = new WritableImage(imageWidth, imageHeight);
        node.snapshot(parameters, wi);

        return wi;

    }

    private static void saveSnapshot(Node node) {

        Image image = createImage(node);

        // save image !!! has bug because of transparency (use approach below) !!!
        // ImageIO.write(SwingFXUtils.fromFXImage( selectedImage.getImage(), null), "jpg", file);

        // save image (without alpha)
        BufferedImage bufImageARGB = SwingFXUtils.fromFXImage(image, null);
        BufferedImage bufImageRGB = new BufferedImage(bufImageARGB.getWidth(), bufImageARGB.getHeight(), BufferedImage.OPAQUE);

        Graphics2D graphics = bufImageRGB.createGraphics();
        graphics.drawImage(bufImageARGB, 0, 0, null);

        try {
            ImageIO.write(bufImageRGB, "jpg", new File(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        graphics.dispose();

        System.out.println( "Image saved: " + fileName);

    }

    public static void main(String[] args) {
        launch(args);
    }
}
以下是快照和图像代码:

所有这些都是通过提交到
线程池的
任务在后台线程上发生的

    Thread.sleep(5000)   // Wait for images to be rendered -
              // they are visually confirmed to be available at  about 1000 ms actually
    javafx.application.Platform.runLater(new Runnable() {
      override def run() = {
//            val snapShot = chart.snapshot(null)
//            val snapShot = scene.snapshot(null)
        val snapShot = pane.snapshot(null,null)
        ImageIO.write(SwingFXUtils.fromFXImage(snapShot, null),
          "jpg", new File(fileName))
正如您所看到的(从注释掉的行中)-我对用于创建快照的对象感到困惑:已经尝试了以上三种方法:

  • 图表
  • 场面
  • 窗格玻璃
结果始终是黑色图像。OOC我还尝试通过

snapshotParameters.setFill(Color.WHITE)
那没有效果

正确的程序是什么

更新我还尝试了
回调
方法:

        pane.snapshot(  // Also tried scene and chart here ..
        new Callback[SnapshotResult, Void]() {
          override def call(result: SnapshotResult): Void = {
            ImageIO.write(SwingFXUtils.fromFXImage(result.getImage, null),
              "jpg", new File(fileName))
            latch.countDown
            null
          }
        },p,null)

同样-仍然是黑色图像

使用这种启发式是相当危险的。但是,您没有提供完整的MCVE。如果您想这样做,可以使用PauseTransition,快照任何节点,然后将图像保存到文件中

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;

import javax.imageio.ImageIO;

public class AutoSnapshot extends Application {

    private static String fileName = "c:/temp/image.jpg";
    private static Color backgroundColor = Color.WHITE;

    @Override
    public void start(Stage primaryStage) {

        AnchorPane root = new AnchorPane();

        // dummy chart
        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();
        xAxis.setLabel("Number of Month");
        final LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis);
        lineChart.setTitle("Stock Monitoring, 2010");
        XYChart.Series series = new XYChart.Series();
        series.setName("My portfolio");
        series.getData().add(new XYChart.Data(1, 23));
        series.getData().add(new XYChart.Data(2, 14));
        series.getData().add(new XYChart.Data(3, 15));
        series.getData().add(new XYChart.Data(4, 24));
        lineChart.getData().add(series);

        root.getChildren().add( lineChart);

        Scene scene = new Scene(root, 800, 600, backgroundColor);
        primaryStage.setScene(scene);
        primaryStage.show();

        Duration delay = Duration.seconds(5);
        PauseTransition pt = new PauseTransition(delay);
        pt.setOnFinished(e -> {
            saveSnapshot(lineChart);
        });
        pt.play();

    }

    public static Image createImage(Node node) {

        WritableImage wi;

        SnapshotParameters parameters = new SnapshotParameters();
        parameters.setFill(backgroundColor);

        int imageWidth = (int) node.getBoundsInLocal().getWidth();
        int imageHeight = (int) node.getBoundsInLocal().getHeight();

        wi = new WritableImage(imageWidth, imageHeight);
        node.snapshot(parameters, wi);

        return wi;

    }

    private static void saveSnapshot(Node node) {

        Image image = createImage(node);

        // save image !!! has bug because of transparency (use approach below) !!!
        // ImageIO.write(SwingFXUtils.fromFXImage( selectedImage.getImage(), null), "jpg", file);

        // save image (without alpha)
        BufferedImage bufImageARGB = SwingFXUtils.fromFXImage(image, null);
        BufferedImage bufImageRGB = new BufferedImage(bufImageARGB.getWidth(), bufImageARGB.getHeight(), BufferedImage.OPAQUE);

        Graphics2D graphics = bufImageRGB.createGraphics();
        graphics.drawImage(bufImageARGB, 0, 0, null);

        try {
            ImageIO.write(bufImageRGB, "jpg", new File(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        graphics.dispose();

        System.out.println( "Image saved: " + fileName);

    }

    public static void main(String[] args) {
        launch(args);
    }
}
导入java.awt.Graphics2D;
导入java.awt.image.buffereImage;
导入java.io.File;
导入java.io.IOException;
导入javafx.animation.PauseTransition;
导入javafx.application.application;
导入javafx.embed.swing.SwingFXUtils;
导入javafx.scene.Node;
导入javafx.scene.scene;
导入javafx.scene.Snapshot参数;
导入javafx.scene.chart.LineChart;
导入javafx.scene.chart.NumberAxis;
导入javafx.scene.chart.XYChart;
导入javafx.scene.image.image;
导入javafx.scene.image.WritableImage;
导入javafx.scene.layout.ancorpane;
导入javafx.scene.paint.Color;
导入javafx.stage.stage;
导入javafx.util.Duration;
导入javax.imageio.imageio;
公共类AutoSnapshot扩展了应用程序{
私有静态字符串fileName=“c:/temp/image.jpg”;
私有静态颜色backgroundColor=Color.WHITE;
@凌驾
公共无效开始(阶段primaryStage){
锚烷根=新锚烷();
//虚拟图表
最终数字axis xAxis=新数字axis();
最终数字axis yAxis=新数字axis();
xAxis.setLabel(“月数”);
最终线形图线形图=新线形图(xAxis,yAxis);
线形图.setTitle(“库存监控,2010年”);
XYChart.Series系列=新的XYChart.Series();
series.setName(“我的投资组合”);
series.getData().add(新的XYChart.Data(1,23));
series.getData().add(新的XYChart.Data(2,14));
series.getData().add(新的XYChart.Data(3,15));
series.getData().add(新的XYChart.Data(4,24));
lineChart.getData().add(系列);
root.getChildren().add(折线图);
场景=新场景(根,800600,背景色);
初级阶段。场景(场景);
primaryStage.show();
持续时间延迟=持续时间。秒(5);
PauseTransition pt=新的PauseTransition(延迟);
零件设置完成(e->{
保存快照(折线图);
});
pt.play();
}
公共静态映像createImage(节点){
可写图像;
SnapshotParameters=新的SnapshotParameters();
参数设置填充(背景色);
int imageWidth=(int)node.getBoundsInLocal().getWidth();
int imageHeight=(int)node.getBoundsInLocal().getHeight();
wi=新的可写图像(图像宽度、图像高度);
节点快照(参数,wi);
返回wi;
}
私有静态void saveSnapshot(节点){
Image Image=createImage(节点);
//保存图像!!!由于透明度问题出现错误(使用下面的方法)!!!
//write(SwingFXUtils.fromFXImage(selectedImage.getImage(),null),“jpg”,文件);
//保存图像(不带alpha)
buffereImage bufImageARGB=SwingFXUtils.fromFXImage(image,null);
buffereImage bufImageRGB=新的buffereImage(bufImageRGB.getWidth(),bufImageRGB.getHeight(),buffereImage.不透明);
Graphics2D graphics=bufImageRGB.createGraphics();
graphics.drawImage(bufImageARGB,0,0,null);
试一试{
write(bufImageRGB,“jpg”,新文件(文件名));
}捕获(IOE异常){
e、 printStackTrace();
}
graphics.dispose();
System.out.println(“保存的图像:“+文件名”);
}
公共静态void main(字符串[]args){
发射(args);
}
}

毕竟。。答案是“jpg”根本不起作用。“png”格式工作正常。

您的代码有以下内容:“保存图像!!!由于透明度而存在错误(使用下面的方法)”。注释掉的代码就是我目前使用的代码。我将首先替换为您的saveSnapshot。该代码只会为您提供错误的颜色,但不会提供黑色图像。我认为问题出在你的线程上。请尝试暂停转换。在替换saveSnapshot/createImage后,我确实看到了白色背景和一些图表。不透明不存在:是否应替换为BuffereImage.TYPE\u BYTE\u BINARY?顺便说一句,我将添加暂停转换。好吧,任何适合你的东西,尽管不透明应该存在。这是Java标准。我发布的代码对我来说很有用。顺便说一句,如果你想要透明度,你需要使用Color.TRANSPARENT作为快照填充参数。我正在向上投票,因为这很有帮助(尽管还有很长的路要走)。JDK8上的java.awt.buffereImage不具有不透明性。