Convert to and from BufferedImage in javafx 2.0

November 20, 2011

While porting Modellus from javafx1.3 using  javafx script to javafx2.0 using java language I ended up creating a class with a few helper methods for converting swing objects to and from javafx objects:

  • Converting from java.awt.color  to javafx.scene.paint.Color and vice versa
  • Converting from java.awt.image.BufferedImage to javafx.scene.image.Image and vice versa

Nothing too fancy but I thought it might come in handy to other people so here’s the code:

public class SwingUtils {

    public static java.awt.Color toAWTColor(javafx.scene.paint.Color fxColor)
    {
        return new java.awt.Color((float)fxColor.getRed(), (float)fxColor.getGreen(), (float)fxColor.getBlue(), (float)fxColor.getOpacity());
    }

    public static javafx.scene.paint.Color fromAWTColor(java.awt.Color awtColor)
    {
        return ColorBuilder.create()
                            .red(awtColor.getRed() / 255.0)
                            .green(awtColor.getGreen() / 255.0)
                            .blue(awtColor.getBlue() / 255.0).build();
    }

    // There is a problem with this implementation: transparent pixels on the BufferedImage aren't converted to transparent pixels on the fxImage.
    public static javafx.scene.image.Image convertToFxImage(java.awt.image.BufferedImage awtImage) {
    	if (Image.impl_isExternalFormatSupported(BufferedImage.class)) {
    		return javafx.scene.image.Image.impl_fromExternalImage(awtImage);
    	} else {
    		return null;
    	}
    }

    public static java.awt.image.BufferedImage convertToAwtImage(javafx.scene.image.Image fxImage) {
    	if (Image.impl_isExternalFormatSupported(BufferedImage.class)) {
    		java.awt.image.BufferedImage awtImage = new BufferedImage((int)fxImage.getWidth(), (int)fxImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
        	return (BufferedImage)fxImage.impl_toExternalImage(awtImage);
    	} else {
    		return null;
    	}
    }
}

This will probably be added on Lombard (next javafx version) as shown by this issue: http://javafx-jira.kenai.com/browse/RT-14038

Advertisement

2 Responses to “Convert to and from BufferedImage in javafx 2.0”


  1. [...] Duque Vieira has put up some simple util methods to convert to and from BufferedImage in JavaFX. Just a word of warning: this uses impl_* [...]


  2. [...] Duque Vieira has put up some simple util methods to convert to and from BufferedImage in JavaFX. Just a word of warning: this uses impl_* [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.