Aaron Johnson Now with 50% less caffeine!

Posted
9 June 2006 @ 7pm

Tagged
Interface Design, J2EE

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

Posted by
Rong Ou
13 November 2006 @ 4pm

That’s pretty cool. I must be one of those 3 people. :)

For the second part, you can also use ChartUtilities if you just want to save the image to a file:

ChartUtilities.saveChartAsPNG(file, chart, width, height, null, true, compressionLevel);


Posted by
Glen Smith
26 March 2007 @ 5pm

And your lucky 3rd person comes from Australia! Thanks for this tip, mate. Just what I was after. Made my day.


Posted by
Lars
28 June 2007 @ 1pm

So im the third person using it? :-)

That did the trick! Thanks Aaron.


Posted by
Karbol
24 September 2008 @ 8am

Hi, I am fourth person… :)


Posted by
Jason
6 November 2008 @ 11am

5th person, thanks!


Leave a Comment

Links: 6-8-2006 Links: 6-12-2006