我正在尝试将一个JavaFX
图像(来自ImageView
)转换为BufferedImage
。我尝试过强制转换等方法,但都不起作用。有人能建议我该如何做吗?
我正在尝试将一个JavaFX
图像(来自ImageView
)转换为BufferedImage
。我尝试过强制转换等方法,但都不起作用。有人能建议我该如何做吗?
使用SwingFXUtils尝试您的运气。 有一个专门用于此目的的方法:
BufferedImage fromFXImage(Image img, BufferedImage bimg)
如果您希望进行内存重用,可以将第二个参数设置为可选的null
并调用它:
BufferedImage image = SwingFXUtils.fromFXImage(fxImage, null);
我觉得为了这个目的导入整个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});
}
}