BufferedImage to JavaFX Image

2022-09-01 06:35:18

我有一个从主显示器截取的图像,我想将其添加到Java FX中,如下所示:ImageView

@FXML
protected ImageView screenshot() throws AWTException, IOException {
    Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
    BufferedImage capture = new Robot().createScreenCapture(screenRect);
    ImageView imageView = new ImageView();
    Image image = capture; //Error
    imageView.setImage(image);
    return imageView;
}

我正在尝试将 设置为,但类型不兼容,也无法强制转换。我该如何纠正这种情况?BufferedImage capturejavafx.scene.image.Image image


答案 1

您可以使用

Image image = SwingFXUtils.toFXImage(capture, null);

答案 2

通常最好的选择是java9或更大....但是在javafx的性能方面,以及在性能较低的设备中,您可以使用这种技术来做魔术,在java8中进行测试Image image = SwingFXUtils.toFXImage(capture, null);

private static Image convertToFxImage(BufferedImage image) {
    WritableImage wr = null;
    if (image != null) {
        wr = new WritableImage(image.getWidth(), image.getHeight());
        PixelWriter pw = wr.getPixelWriter();
        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                pw.setArgb(x, y, image.getRGB(x, y));
            }
        }
    }

    return new ImageView(wr).getImage();
}

推荐