BufferedImage to JavaFX image

后端 未结 2 1202
小蘑菇
小蘑菇 2020-12-29 03:29

I have an image I screenshot from the primary monitor and I want to add it to a Java FX ImageView as so:

@FXML
protected ImageView screenshot()          


        
相关标签:
2条回答
  • 2020-12-29 04:10

    You can use

    Image image = SwingFXUtils.toFXImage(capture, null);
    
    0 讨论(0)
  • 2020-12-29 04:10

    normally the best choice is Image image = SwingFXUtils.toFXImage(capture, null); in java9 or bigger.... but in matter of performance in javafx, also in devices with low performance, you can use this technique that will do the magic, tested in java8

    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();
    }
    
    0 讨论(0)
提交回复
热议问题