Leon Atherton Leon is a developer at IDRsolutions and product manager for BuildVu. He oversees the BuildVu product strategy and roadmap in addition to spending lots of time writing code.

Are you a Java Developer working with PDF files?

Find out why you should be using JPedal

How to convert from BufferedImage to JavaFX 2.2 Image

50 sec read

Until recently, if you wanted to load a BufferedImage in JavaFX you were out of luck – the only way to do it was to write out the BufferedImage to disk and then read it back in as a JavaFX Image.

But, in August when JavaFX 2.2 was released, the update included a class called WritableImage which extends Image. Along with PixelWriter and PixelReader classes, this gives us greater control over images in JavaFX.

Using the PixelWriter and the getRGB method of BufferedImage, we are now able to read a BufferedImage into a WritableImage. As WritableImage extends Image, we can now use this however we would an Image!

Here’s how:

        BufferedImage bf = null;
        try {
            bf = ImageIO.read(new File("C:/location/of/image.png"));
        } catch (IOException ex) {
            System.out.println("Image failed to load.");
        }

        WritableImage wr = null;
        if (bf != null) {
            wr = new WritableImage(bf.getWidth(), bf.getHeight());
            PixelWriter pw = wr.getPixelWriter();
            for (int x = 0; x < bf.getWidth(); x++) {
                for (int y = 0; y < bf.getHeight(); y++) {
                    pw.setArgb(x, y, bf.getRGB(x, y));
                }
            }
        }

        ImageView imView = new ImageView(wr);

Alternatively, you could use the toFXImage method from SwingFXUtils, but where’s the fun in that?

This article was inspired by converting the PageFlow mode in out Java PDF Viewer from Java3D to JavaFX. I have written several articles on converting our Java3D usage into JavaFX and you can read the other articles here.



Our software libraries allow you to

Convert PDF to HTML in Java
Convert PDF Forms to HTML5 in Java
Convert PDF Documents to an image in Java
Work with PDF Documents in Java
Read and Write AVIF, HEIC, WEBP and other image formats
Leon Atherton Leon is a developer at IDRsolutions and product manager for BuildVu. He oversees the BuildVu product strategy and roadmap in addition to spending lots of time writing code.