15

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?

Sufian
  • 6,405
  • 16
  • 66
  • 120
Piet Jetse
  • 388
  • 1
  • 5
  • 16

2 Answers2

35

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);
lukk
  • 3,164
  • 1
  • 30
  • 36
  • Doesn't work on raspberry pi see https://stackoverflow.com/questions/50900945/swingfxutils-alternative-for-image-serialization-javafx-swing-raspberryi – Wolfgang Fahl Feb 23 '19 at 18:41
0

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});
    }
}
Luna
  • 193
  • 1
  • 9
  • 2
    And what exactly do you think you gain by that? Using BufferedImage pulls in the whole java.desktop module anyway. – mipa May 04 '22 at 14:59
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 05 '22 at 12:16