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?
You can use
Image image = SwingFXUtils.toFXImage(capture, null);
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With