FusionCharts is a flash-based animated charting package. One of its recent features is the ability to export the chart images so end users can save them to disk. Unfortunately the sample code provided gives only PHP and C# examples of how to do this, which isn't so handy if you're using Java. So, in the public interest, here is a Java of that code:
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
// Extract parameters
int width = Integer.parseInt(req.getParameter("width")) - 1;
int height = Integer.parseInt(req.getParameter("height"));
String bgColorStr = req.getParameter("bgcolor");
int bgColor = (bgColorStr == null || bgColorStr.length() == 0) ? 0xffffff : Integer.parseInt(bgColorStr, 16);
String data = req.getParameter("data");
// Build the bitmap image
BufferedImage image = buildBitmap(width, height, bgColor, data);
// Compress the image as a JPEG
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam writerParam = writer.getDefaultWriteParam();
writerParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writerParam.setCompressionQuality(0.95f);
// Stream the image to the user agent
resp.addHeader("Content-Disposition", "attachment; filename=\"FusionCharts.jpg\"");
resp.setContentType("image/jpeg");
ImageOutputStream imageOut = ImageIO.createImageOutputStream(resp.getOutputStream());
writer.setOutput(imageOut);
writer.write(null, new IIOImage(image, null, null), writerParam);
imageOut.flush();
imageOut.close();
}
private BufferedImage buildBitmap(int width, int height, int bgColor, String data)
{
BufferedImage chart = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
String[] rows = data.split(";");
int colIdx = 0;
for (int rowIdx = 0; rowIdx < rows.length; rowIdx++)
{
// Split individual pixels
String[] pixels = rows[rowIdx].split(",");
colIdx = 0;
for (int pixelIdx = 0; pixelIdx < pixels.length; pixelIdx++)
{
// Split the color and repeat factor
String[] clrs = pixels[pixelIdx].split("_");
int color = ("".equals(clrs[0])) ? bgColor : Integer.parseInt(clrs[0], 16);
int repeatFactor = Integer.parseInt(clrs[1]);
// Set the color the specified number of times
for (int repeatCount = 0; repeatCount < repeatFactor; repeatCount++, colIdx++)
{
chart.setRGB(colIdx, rowIdx, color);
}
}
}
return chart;
}
Note: I think there's a bug in the Flash image exporter. It looks like it's reporting the width of the image to be 1 pixel greater than whan it actually is, hence the expression Integer.parseInt(req.getParameter("width")) - 1.