BufferedImage 到 JavaFX 图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30970005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
BufferedImage to JavaFX image
提问by Nanor
I have an image I screenshot from the primary monitor and I want to add it to a Java FX ImageView
as so:
我有一张从主监视器截取的图像,我想将其添加到 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;
}
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?
我正在尝试将 设置为BufferedImage capture
,javafx.scene.image.Image image
但类型不兼容,我也无法投射它。我该如何纠正?
采纳答案by Reimeus
You can use
您可以使用
Image image = SwingFXUtils.toFXImage(capture, null);
回答by Dan
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
通常最好的选择是Image image = SwingFXUtils.toFXImage(capture, null);
在 java9 或更大......但在 javafx 的性能问题上,也在性能低的设备中,你可以使用这种技术来实现魔法,在 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();
}