将 JavaFX 图像转换为缓冲图像

2022-09-03 17:33:57

我正在尝试将图像(从)转换为.我尝试了铸造和其他东西,但没有任何效果。有人可以建议我应该如何做到这一点吗?JavaFXImageViewBufferedImage


答案 1

试试你的运气与SwingFXUtils。有一种方法可用于此目的:

BufferedImage fromFXImage(Image img, BufferedImage bimg)

您可以使用第二个参数调用它,因为它是可选的(出于内存重用原因而存在):null

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

答案 2

我发现仅仅为了这个而导入整个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});
    }
}

推荐