将JavaFX图像转换为BufferedImage

15

我正在尝试将一个JavaFX图像(来自ImageView)转换为BufferedImage。我尝试过强制转换等方法,但都不起作用。有人能建议我该如何做吗?

2个回答

35

使用SwingFXUtils尝试您的运气。 有一个专门用于此目的的方法:


BufferedImage fromFXImage(Image img, BufferedImage bimg)

如果您希望进行内存重用,可以将第二个参数设置为可选的null并调用它:

BufferedImage image = SwingFXUtils.fromFXImage(fxImage, null);

无法在树莓派上运行,请参见 https://stackoverflow.com/questions/50900945/swingfxutils-alternative-for-image-serialization-javafx-swing-raspberryi。 - Wolfgang Fahl

0

我觉得为了这个目的导入整个Java Swing库是不明智的。还有其他解决方案。我的解决方案可能不是很好,但我认为它比导入一个全新的库要好。

Image image = /* your image */;
int width = (int) image.getWidth();
int height = (int) image.getHeight();
int pixels[] = new int[width * height];

// Load the image's data into an array
// You need to MAKE SURE the image's pixel format is compatible with IntBuffer
image.getPixelReader().getPixels(
    0, 0, width, height, 
    (WritablePixelFormat<IntBuffer>) image.getPixelReader().getPixelFormat(),
    pixels, 0, width
);

BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
        // There may be better ways to do this
        // You'll need to make sure your image's format is correct here
        var pixel = pixels[y * width + x];
        int r = (pixel & 0xFF0000) >> 16;
        int g = (pixel & 0xFF00) >> 8;
        int b = (pixel & 0xFF) >> 0;

        bufferedImage.getRaster().setPixel(x, y, new int[]{r, g, b});
    }
}

2
你认为这样做能获得什么好处呢?使用BufferedImage无论如何都会引入整个java.desktop模块。 - mipa
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接