Transparent PNG Charts with JFreeChart
If you’re one of the 3 people in the world that need to create a transparent PNG image using JFreeChart, you’ve come to the right place:
JFreeChart chart = ChartFactory.createXYBarChart(...);
chart.setBackgroundPaint(new Color(255,255,255,0));
...
KeypointPNGEncoderAdapter encoder = new KeypointPNGEncoderAdapter();
encoder.setEncodingAlpha(true);
encoder.encode(chart.createBufferedImage(width, height, BufferedImage.BITMASK, null));
The key is that you must use the KeyPointPNGEncoderAdapter, which is slower for big charts, but is the only one of the two PNG encoders that JFree ships with that has the ability to do alpha transparency. On systems running JDK 1.4 and above, the ImageEncoderFactory will return the SunPNGEncoderAdapter, which does not support alpha transparency.
Also, if you’re planning on using alpha transparency in a web application that needs to support IE, you’ll want to check out this JavaScript fix by Bob Osola.
5 Comments