Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedImage to JavaFX image

Tags:

java

javafx

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() 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; } 

I'm trying to set the BufferedImage capture to javafx.scene.image.Image image but the types are incompatible nor am I able to cast it. How can I rectify this?

like image 492
Nanor Avatar asked Jun 21 '15 22:06

Nanor


2 Answers

You can use

Image image = SwingFXUtils.toFXImage(capture, null); 
like image 146
Reimeus Avatar answered Sep 24 '22 14:09

Reimeus


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(); } 
like image 35
Dan Avatar answered Sep 21 '22 14:09

Dan