版本1:jfreechart-1.0.9
生成图片代码如下:
ChartUtilities.writeChartAsJPEG(out, chart, 500, 400);
得到的图片显示如下,出现不正常的红色背景
jfreechart-1.0.9生成图片各主要代码如下:
JFreeChart类
public BufferedImage createBufferedImage(int width, int height, ChartRenderingInfo info) { return createBufferedImage(width, height, 2, info); } public BufferedImage createBufferedImage(int width, int height, int imageType, ChartRenderingInfo info) { BufferedImage image = new BufferedImage(width, height, imageType); Graphics2D g2 = image.createGraphics(); draw(g2, new Rectangle2D.Double(0.0D, 0.0D, width, height), null, info); g2.dispose(); return image; }
如上所述,创建BufferedImage的时候,使用的iamgeType是2,也就是BufferedImage.TYPE_INT_ARGB格式。
解决方法一:手动设置imageType为1(即BufferedImage.TYPE_INT_RGB),如下代码:
BufferedImage bi = chart.createBufferedImage(500, 400, 1, null); ImageIO.write(bi, "jpeg", out);
解决方法二:升级jfreechart到1.0.10,该版本中JFreeChart中的createBufferedImage代码如下:
public static void writeChartAsJPEG(OutputStream out, float quality, JFreeChart chart, int width, int height, ChartRenderingInfo info) throws IOException { if (chart == null) { throw new IllegalArgumentException("Null 'chart' argument."); } BufferedImage image = chart.createBufferedImage(width, height, 1, info); EncoderUtil.writeBufferedImage(image, "jpeg", out, quality); }
1.0.10版本在调用JFreeChart的createBufferedImage默认使用了imageType为BufferedImage.TYPE_INT_RGB
调整后生成的图片如下: