如何将GRAL图输出到JPG?

时间:2013-12-27 16:38:10

标签: java jpeg graphics2d

我正在尝试使用以下内容将示例GRAL Pie plot导出为jpg:

private byte[] getJpg() throws IOException {
    BufferedImage bImage = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bImage.createGraphics();
    DrawingContext drawingContext = new DrawingContext(g2d, DrawingContext.Quality.QUALITY,
            DrawingContext.Target.BITMAP);
    PiePlot plot = getPlot();
    plot.draw(drawingContext);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(bImage, "jpg", baos);
    baos.flush();
    byte[] bytes = baos.toByteArray();
    baos.close();
    return bytes;
}

但它呈现为带有一些图例信息的黑色矩形(图例没问题)。谁知道从GRAL绘图中渲染JPG的正确方法?

1 个答案:

答案 0 :(得分:7)

当然,我找到了一个内置的解决方案,DrawableWriter。现在导出如下:

private byte[] getJpg() throws IOException {
        BufferedImage bImage = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = (Graphics2D) bImage.getGraphics();
        DrawingContext context = new DrawingContext(g2d);
        PiePlot plot = getPlot();
        plot.draw(context);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DrawableWriter wr = DrawableWriterFactory.getInstance().get("image/jpeg");
        wr.write(plot, baos, 800, 600);
        baos.flush();
        byte[] bytes = baos.toByteArray();
        baos.close();
        return bytes;
    }

感谢开发人员!一切都已经完成。