I'm trying to convert an JavaFX
Image(from ImageView
) to an BufferedImage
. I tried casting and stuff but nothing works. Can someone suggest how i should do this?
Try your luck with SwingFXUtils . There is a method for that purpose:
BufferedImage fromFXImage(Image img, BufferedImage bimg)
You can call it with second parameter null
, as it is optional (exists for memory reuse reason):
BufferedImage image = SwingFXUtils.fromFXImage(fxImage, null);
I find it insane to import the entirety of Java Swing only for this. There are other solutions. My solution below is not too great, but I think it's better than importing a completely new library.
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});
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.