Example usage for org.jfree.chart ChartUtilities encodeAsPNG

List of usage examples for org.jfree.chart ChartUtilities encodeAsPNG

Introduction

In this page you can find the example usage for org.jfree.chart ChartUtilities encodeAsPNG.

Prototype

public static byte[] encodeAsPNG(BufferedImage image) throws IOException 

Source Link

Document

Encodes a BufferedImage to PNG format.

Usage

From source file:com.googlecode.psiprobe.controllers.RenderChartController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    final int SERIES_NUM = 9; // the max number of series

    ////from   w  w  w.  j  a  va2  s . co m
    // get Series Color from the request
    //
    int[] seriesColor = new int[SERIES_NUM];
    seriesColor[0] = Utils.toIntHex(request.getParameter("s1c"), 0x9bd2fb);
    seriesColor[1] = Utils.toIntHex(request.getParameter("s2c"), 0xFF0606);
    for (int i = 2; i < SERIES_NUM; i++) {
        seriesColor[i] = Utils.toIntHex(request.getParameter("s" + (i + 1) + "c"), -1);
    }

    //
    // get Series Outline Color from the request
    //
    int[] seriesOutlineColor = new int[SERIES_NUM];
    seriesOutlineColor[0] = Utils.toIntHex(request.getParameter("s1o"), 0x0665aa);
    seriesOutlineColor[1] = Utils.toIntHex(request.getParameter("s2o"), 0x9d0000);
    for (int i = 2; i < SERIES_NUM; i++) {
        seriesOutlineColor[i] = Utils.toIntHex(request.getParameter("s" + (i + 1) + "o"), -1);
    }

    //
    // background color
    //
    int backgroundColor = Utils.toIntHex(request.getParameter("bc"), 0xFFFFFF);
    //
    // grid color
    //
    int gridColor = Utils.toIntHex(request.getParameter("gc"), 0);
    //
    // X axis title
    //
    String xLabel = ServletRequestUtils.getStringParameter(request, "xl", "");
    //
    // Y axis title
    //
    String yLabel = ServletRequestUtils.getStringParameter(request, "yl", "");
    //
    // image width
    //
    int width = ServletRequestUtils.getIntParameter(request, "xz", 800);
    //
    // image height
    //
    int height = ServletRequestUtils.getIntParameter(request, "yz", 400);
    //
    // show legend?
    //
    boolean showLegend = ServletRequestUtils.getBooleanParameter(request, "l", true);
    //
    // Series provider
    //
    String provider = ServletRequestUtils.getStringParameter(request, "p", null);
    //
    // Chart type
    //
    String chartType = ServletRequestUtils.getStringParameter(request, "ct", "area");

    DefaultTableXYDataset ds = new DefaultTableXYDataset();

    if (provider != null) {
        Object o = getApplicationContext().getBean(provider);
        if (o instanceof SeriesProvider) {
            ((SeriesProvider) o).populate(ds, statsCollection, request);
        } else {
            logger.error("SeriesProvider \"" + provider + "\" does not implement " + SeriesProvider.class);
        }

    }

    //
    // Build series data from the give statistic
    //

    JFreeChart chart = null;
    if ("area".equals(chartType)) {

        chart = ChartFactory.createXYAreaChart("", xLabel, yLabel, ds, PlotOrientation.VERTICAL, showLegend,
                false, false);

        ((XYAreaRenderer) chart.getXYPlot().getRenderer()).setOutline(true);

    } else if ("stacked".equals(chartType)) {

        chart = ChartFactory.createStackedXYAreaChart("", xLabel, yLabel, ds, PlotOrientation.VERTICAL,
                showLegend, false, false);

    } else if ("line".equals(chartType)) {

        chart = ChartFactory.createXYLineChart("", xLabel, yLabel, ds, PlotOrientation.VERTICAL, showLegend,
                false, false);

        final XYLine3DRenderer renderer = new XYLine3DRenderer();
        renderer.setDrawOutlines(true);
        renderer.setLinesVisible(true);
        renderer.setShapesVisible(true);
        renderer.setStroke(new BasicStroke(2));
        renderer.setXOffset(1);
        renderer.setYOffset(1);
        chart.getXYPlot().setRenderer(renderer);
    }

    if (chart != null) {
        chart.setAntiAlias(true);
        chart.setBackgroundPaint(new Color(backgroundColor));
        for (int i = 0; i < SERIES_NUM; i++) {
            if (seriesColor[i] >= 0) {
                chart.getXYPlot().getRenderer().setSeriesPaint(i, new Color(seriesColor[i]));
            }
            if (seriesOutlineColor[i] >= 0) {
                chart.getXYPlot().getRenderer().setSeriesOutlinePaint(i, new Color(seriesOutlineColor[i]));
            }
        }
        chart.getXYPlot().setDomainGridlinePaint(new Color(gridColor));
        chart.getXYPlot().setRangeGridlinePaint(new Color(gridColor));
        chart.getXYPlot().setDomainAxis(0, new DateAxis());
        chart.getXYPlot().setDomainAxis(1, new DateAxis());
        chart.getXYPlot().setInsets(new RectangleInsets(-15, 0, 0, 10));

        response.setHeader("Content-type", "image/png");
        response.getOutputStream().write(ChartUtilities.encodeAsPNG(chart.createBufferedImage(width, height)));
    }

    return null;
}

From source file:psiprobe.controllers.RenderChartController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    final int seriesMaxCount = 9; // the max number of series

    // get Series Color from the request
    int[] seriesColor = new int[seriesMaxCount];
    seriesColor[0] = Utils.toIntHex(request.getParameter("s1c"), 0x9bd2fb);
    seriesColor[1] = Utils.toIntHex(request.getParameter("s2c"), 0xFF0606);
    for (int i = 2; i < seriesMaxCount; i++) {
        seriesColor[i] = Utils.toIntHex(request.getParameter("s" + (i + 1) + "c"), -1);
    }//from  w w w . ja va  2  s. com

    // get Series Outline Color from the request
    int[] seriesOutlineColor = new int[seriesMaxCount];
    seriesOutlineColor[0] = Utils.toIntHex(request.getParameter("s1o"), 0x0665aa);
    seriesOutlineColor[1] = Utils.toIntHex(request.getParameter("s2o"), 0x9d0000);
    for (int i = 2; i < seriesMaxCount; i++) {
        seriesOutlineColor[i] = Utils.toIntHex(request.getParameter("s" + (i + 1) + "o"), -1);
    }

    // background color
    int backgroundColor = Utils.toIntHex(request.getParameter("bc"), 0xFFFFFF);

    // grid color
    int gridColor = Utils.toIntHex(request.getParameter("gc"), 0);

    // X axis title
    String labelX = ServletRequestUtils.getStringParameter(request, "xl", "");

    // Y axis title
    String labelY = ServletRequestUtils.getStringParameter(request, "yl", "");

    // image width
    int width = ServletRequestUtils.getIntParameter(request, "xz", 800);

    // image height
    int height = ServletRequestUtils.getIntParameter(request, "yz", 400);

    // show legend?
    boolean showLegend = ServletRequestUtils.getBooleanParameter(request, "l", true);

    // Series provider
    String provider = ServletRequestUtils.getStringParameter(request, "p", null);

    // Chart type
    String chartType = ServletRequestUtils.getStringParameter(request, "ct", "area");

    DefaultTableXYDataset ds = new DefaultTableXYDataset();

    if (provider != null) {
        Object series = getApplicationContext().getBean(provider);
        if (series instanceof SeriesProvider) {
            ((SeriesProvider) series).populate(ds, statsCollection, request);
        } else {
            logger.error("SeriesProvider '{}' does not implement '{}'", provider, SeriesProvider.class);
        }

    }

    // Build series data from the give statistic
    JFreeChart chart = null;
    if ("area".equals(chartType)) {
        chart = ChartFactory.createXYAreaChart("", labelX, labelY, ds, PlotOrientation.VERTICAL, showLegend,
                false, false);

        ((XYAreaRenderer) chart.getXYPlot().getRenderer()).setOutline(true);

    } else if ("stacked".equals(chartType)) {
        chart = ChartFactory.createStackedXYAreaChart("", labelX, labelY, ds, PlotOrientation.VERTICAL,
                showLegend, false, false);

    } else if ("line".equals(chartType)) {
        chart = ChartFactory.createXYLineChart("", labelX, labelY, ds, PlotOrientation.VERTICAL, showLegend,
                false, false);

        final XYLine3DRenderer renderer = new XYLine3DRenderer();
        renderer.setDrawOutlines(true);
        for (int i = 0; i < seriesMaxCount; i++) {
            renderer.setSeriesLinesVisible(i, true);
            renderer.setSeriesShapesVisible(i, true);
            renderer.setSeriesStroke(i, new BasicStroke(2));
        }
        renderer.setXOffset(1);
        renderer.setYOffset(1);
        chart.getXYPlot().setRenderer(renderer);
    }

    if (chart != null) {
        chart.setAntiAlias(true);
        chart.setBackgroundPaint(new Color(backgroundColor));
        for (int i = 0; i < seriesMaxCount; i++) {
            if (seriesColor[i] >= 0) {
                chart.getXYPlot().getRenderer().setSeriesPaint(i, new Color(seriesColor[i]));
            }
            if (seriesOutlineColor[i] >= 0) {
                chart.getXYPlot().getRenderer().setSeriesOutlinePaint(i, new Color(seriesOutlineColor[i]));
            }
        }
        chart.getXYPlot().setDomainGridlinePaint(new Color(gridColor));
        chart.getXYPlot().setRangeGridlinePaint(new Color(gridColor));
        chart.getXYPlot().setDomainAxis(0, new DateAxis());
        chart.getXYPlot().setDomainAxis(1, new DateAxis());
        chart.getXYPlot().setInsets(new RectangleInsets(-15, 0, 0, 10));

        response.setHeader("Content-type", "image/png");
        response.getOutputStream().write(ChartUtilities.encodeAsPNG(chart.createBufferedImage(width, height)));
    }

    return null;
}

From source file:com.esofthead.mycollab.ui.chart.JFreeChartWrapper.java

@Override
public Resource getSource() {
    if (res == null) {
        StreamSource streamSource = new StreamResource.StreamSource() {
            private ByteArrayInputStream bytestream = null;

            ByteArrayInputStream getByteStream() {
                if (chart != null && bytestream == null) {
                    int width = getGraphWidth();
                    int height = getGraphHeight();

                    if (mode == RenderingMode.SVG) {
                        // Create an instance of the SVG Generator
                        SVGGraphics2D svgGenerator = new SVGGraphics2D(width, height);

                        // draw the chart in the SVG generator
                        chart.draw(svgGenerator, new Rectangle(width, height));
                        // create an xml string in svg format from the drawing
                        String drawingSVG = svgGenerator.getSVGElement();
                        return new ByteArrayInputStream(drawingSVG.getBytes(StandardCharsets.UTF_8));
                    } else {
                        // Draw png to bytestream
                        try {
                            byte[] bytes = ChartUtilities.encodeAsPNG(chart.createBufferedImage(width, height));
                            bytestream = new ByteArrayInputStream(bytes);
                        } catch (Exception e) {
                            log.error("Error while generating PNG chart", e);
                        }// w  w w . j a va 2 s  . co  m

                    }

                } else {
                    bytestream.reset();
                }
                return bytestream;
            }

            @Override
            public InputStream getStream() {
                return getByteStream();
            }
        };

        res = new StreamResource(streamSource, String.format("graph%d", System.currentTimeMillis())) {

            @Override
            public int getBufferSize() {
                if (getStreamSource().getStream() != null) {
                    try {
                        return getStreamSource().getStream().available();
                    } catch (IOException e) {
                        log.warn("Error while get stream info", e);
                        return 0;
                    }
                } else {
                    return 0;
                }
            }

            @Override
            public long getCacheTime() {
                return 0;
            }

            @Override
            public String getFilename() {
                if (mode == RenderingMode.PNG) {
                    return super.getFilename() + ".png";
                } else {
                    return super.getFilename() + (gzipEnabled ? ".svgz" : ".svg");
                }
            }

            @Override
            public DownloadStream getStream() {
                DownloadStream downloadStream = new DownloadStream(getStreamSource().getStream(), getMIMEType(),
                        getFilename());
                if (gzipEnabled && mode == RenderingMode.SVG) {
                    downloadStream.setParameter("Content-Encoding", "gzip");
                }
                return downloadStream;
            }

            @Override
            public String getMIMEType() {
                if (mode == RenderingMode.PNG) {
                    return "image/png";
                } else {
                    return "image/svg+xml";
                }
            }
        };
    }
    return res;
}

From source file:web.diva.server.model.pca.PCAImageGenerator.java

@SuppressWarnings("CallToPrintStackTrace")
public String toImage() {
    image = (BufferedImage) plot.getImage();

    byte[] imageData = null;
    try {/*from  w w w .j  a v  a  2  s.  co  m*/
        imageData = ChartUtilities.encodeAsPNG(image);
    } catch (Exception e) {
        e.printStackTrace();
    }
    String base64 = Base64.encodeBase64String(imageData);
    base64 = "data:image/png;base64," + base64;

    return base64;

}

From source file:probe.com.view.body.quantcompare.PieChart.java

private String saveToFile(final JFreeChart chart, final double width, final double height) {
    byte imageData[];
    try {/* w w  w .  j a  v  a2 s.  c o  m*/

        imageData = ChartUtilities
                .encodeAsPNG(chart.createBufferedImage((int) width, (int) height, chartRenderingInfo));
        String base64 = Base64.encodeBase64String(imageData);
        base64 = "data:image/png;base64," + base64;
        return base64;
    } catch (IOException e) {
        System.err.println("at error " + e.getMessage());
    }
    return "";
}

From source file:velo.ejb.seam.action.HomeActionsBean.java

public void createChart() {
    ResourceList rl = new ResourceList();
    rl.getResource().setActive(true);/*from w w  w .  ja v  a 2  s  . c  om*/
    rl.initialize();
    List<Resource> resources = rl.getResultList();

    //Retrieve a list of tasks from last day
    TaskList tl = new TaskList();
    List<Task> tasks = tl.getResultList();

    //build the summaries
    Map<String, Long> rTasks = new HashMap<String, Long>();

    for (Task currTask : tasks) {
        if (currTask instanceof ResourceTask) {
            ResourceTask rt = (ResourceTask) currTask;

            if (!rTasks.containsKey(rt.getResourceUniqueName())) {
                rTasks.put(rt.getResourceUniqueName(), new Long(0));
            }

            rTasks.put(rt.getResourceUniqueName(), rTasks.get(rt.getResourceUniqueName()) + 1);
        }
    }

    final DefaultPieDataset dataset = new DefaultPieDataset();
    for (Resource currResource : resources) {
        if (rTasks.containsKey(currResource.getUniqueName())) {
            dataset.setValue(currResource.getDisplayName() + "("
                    + rTasks.get(currResource.getUniqueName()).longValue() + ")",
                    rTasks.get(currResource.getUniqueName()));
        } else {
            dataset.setValue(currResource.getDisplayName() + "(0)", 0);
        }

    }

    final JFreeChart chart = ChartFactory.createPieChart("Tasks Amount (1 last day) per resource", // chart title
            dataset, // dataset
            true, // include legend
            true, false);
    final PiePlot plot = (PiePlot) chart.getPlot();
    plot.setNoDataMessage("No data available");

    try {
        this.chart = ChartUtilities.encodeAsPNG(chart.createBufferedImage(400, 400));
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.esofthead.mycollab.community.ui.chart.JFreeChartWrapper.java

@Override
public Resource getSource() {
    if (res == null) {
        StreamSource streamSource = new StreamResource.StreamSource() {
            private ByteArrayInputStream bytestream = null;

            ByteArrayInputStream getByteStream() {
                if (chart != null && bytestream == null) {
                    int width = getGraphWidth();
                    int height = getGraphHeight();

                    if (mode == RenderingMode.SVG) {

                        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = null;
                        try {
                            docBuilder = docBuilderFactory.newDocumentBuilder();
                        } catch (ParserConfigurationException e1) {
                            throw new RuntimeException(e1);
                        }/*w  w  w  .  j  ava  2s  .  c  om*/
                        Document document = docBuilder.newDocument();
                        Element svgelem = document.createElement("svg");
                        document.appendChild(svgelem);

                        // Create an instance of the SVG Generator
                        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

                        // draw the chart in the SVG generator
                        chart.draw(svgGenerator, new Rectangle(width, height));
                        Element el = svgGenerator.getRoot();
                        el.setAttributeNS(null, "viewBox", "0 0 " + width + " " + height + "");
                        el.setAttributeNS(null, "style", "width:100%;height:100%;");
                        el.setAttributeNS(null, "preserveAspectRatio", getSvgAspectRatio());

                        // Write svg to buffer
                        ByteArrayOutputStream baoutputStream = new ByteArrayOutputStream();
                        Writer out;
                        try {
                            OutputStream outputStream = gzipEnabled ? new GZIPOutputStream(baoutputStream)
                                    : baoutputStream;
                            out = new OutputStreamWriter(outputStream, "UTF-8");
                            /*
                            * don't use css, FF3 can'd deal with the result
                            * perfectly: wrong font sizes
                            */
                            boolean useCSS = false;
                            svgGenerator.stream(el, out, useCSS, false);
                            outputStream.flush();
                            outputStream.close();
                            bytestream = new ByteArrayInputStream(baoutputStream.toByteArray());
                        } catch (Exception e) {
                            log.error("Error while generating SVG chart", e);
                        }
                    } else {
                        // Draw png to bytestream
                        try {
                            byte[] bytes = ChartUtilities.encodeAsPNG(chart.createBufferedImage(width, height));
                            bytestream = new ByteArrayInputStream(bytes);
                        } catch (Exception e) {
                            log.error("Error while generating PNG chart", e);
                        }

                    }

                } else {
                    bytestream.reset();
                }
                return bytestream;
            }

            @Override
            public InputStream getStream() {
                return getByteStream();
            }
        };

        res = new StreamResource(streamSource, String.format("graph%d", System.currentTimeMillis())) {

            @Override
            public int getBufferSize() {
                if (getStreamSource().getStream() != null) {
                    try {
                        return getStreamSource().getStream().available();
                    } catch (IOException e) {
                        log.warn("Error while get stream info", e);
                        return 0;
                    }
                } else {
                    return 0;
                }
            }

            @Override
            public long getCacheTime() {
                return 0;
            }

            @Override
            public String getFilename() {
                if (mode == RenderingMode.PNG) {
                    return super.getFilename() + ".png";
                } else {
                    return super.getFilename() + (gzipEnabled ? ".svgz" : ".svg");
                }
            }

            @Override
            public DownloadStream getStream() {
                DownloadStream downloadStream = new DownloadStream(getStreamSource().getStream(), getMIMEType(),
                        getFilename());
                if (gzipEnabled && mode == RenderingMode.SVG) {
                    downloadStream.setParameter("Content-Encoding", "gzip");
                }
                return downloadStream;
            }

            @Override
            public String getMIMEType() {
                if (mode == RenderingMode.PNG) {
                    return "image/png";
                } else {
                    return "image/svg+xml";
                }
            }
        };
    }
    return res;
}

From source file:org.vaadin.addon.JFreeChartWrapper.java

@Override
public Resource getSource() {
    if (res == null) {
        StreamSource streamSource = new StreamResource.StreamSource() {
            private ByteArrayInputStream bytestream = null;

            ByteArrayInputStream getByteStream() {
                if (chart != null && bytestream == null) {
                    int widht = getGraphWidth();
                    int height = getGraphHeight();

                    if (mode == RenderingMode.SVG) {

                        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = null;
                        try {
                            docBuilder = docBuilderFactory.newDocumentBuilder();
                        } catch (ParserConfigurationException e1) {
                            throw new RuntimeException(e1);
                        }//from w w  w.  j  av  a2 s.  c om
                        Document document = docBuilder.newDocument();
                        Element svgelem = document.createElement("svg");
                        document.appendChild(svgelem);

                        // Create an instance of the SVG Generator
                        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

                        // draw the chart in the SVG generator
                        chart.draw(svgGenerator, new Rectangle(widht, height));
                        Element el = svgGenerator.getRoot();
                        el.setAttributeNS(null, "viewBox", "0 0 " + widht + " " + height + "");
                        el.setAttributeNS(null, "style", "width:100%;height:100%;");
                        el.setAttributeNS(null, "preserveAspectRatio", getSvgAspectRatio());

                        // Write svg to buffer
                        ByteArrayOutputStream baoutputStream = new ByteArrayOutputStream();
                        Writer out;
                        try {
                            OutputStream outputStream = gzipEnabled ? new GZIPOutputStream(baoutputStream)
                                    : baoutputStream;
                            out = new OutputStreamWriter(outputStream, "UTF-8");
                            /*
                             * don't use css, FF3 can'd deal with the result
                             * perfectly: wrong font sizes
                             */
                            boolean useCSS = false;
                            svgGenerator.stream(el, out, useCSS, false);
                            outputStream.flush();
                            outputStream.close();
                            bytestream = new ByteArrayInputStream(baoutputStream.toByteArray());
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (SVGGraphics2DIOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        // Draw png to bytestream
                        try {
                            byte[] bytes = ChartUtilities.encodeAsPNG(chart.createBufferedImage(widht, height));
                            bytestream = new ByteArrayInputStream(bytes);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }

                } else {
                    bytestream.reset();
                }
                return bytestream;
            }

            @Override
            public InputStream getStream() {
                return getByteStream();
            }
        };

        res = new StreamResource(streamSource, String.format("graph%d", System.currentTimeMillis())) {

            @Override
            public int getBufferSize() {
                if (getStreamSource().getStream() != null) {
                    try {
                        return getStreamSource().getStream().available();
                    } catch (IOException e) {
                        return 0;
                    }
                } else {
                    return 0;
                }
            }

            @Override
            public long getCacheTime() {
                return 0;
            }

            @Override
            public String getFilename() {
                if (mode == RenderingMode.PNG) {
                    return super.getFilename() + ".png";
                } else {
                    return super.getFilename() + (gzipEnabled ? ".svgz" : ".svg");
                }
            }

            @Override
            public DownloadStream getStream() {
                DownloadStream downloadStream = new DownloadStream(getStreamSource().getStream(), getMIMEType(),
                        getFilename());
                if (gzipEnabled && mode == RenderingMode.SVG) {
                    downloadStream.setParameter("Content-Encoding", "gzip");
                }
                return downloadStream;
            }

            @Override
            public String getMIMEType() {
                if (mode == RenderingMode.PNG) {
                    return "image/png";
                } else {
                    return "image/svg+xml";
                }
            }
        };
    }
    return res;
}

From source file:com.iontorrent.vaadin.utils.JFreeChartWrapper.java

@Override
public Resource getSource() {
    if (res == null) {
        res = new ApplicationResource() {

            private ByteArrayInputStream bytestream = null;

            ByteArrayInputStream getByteStream() {
                if (chart != null && bytestream == null) {
                    int widht = getGraphWidth();
                    int height = getGraphHeight();
                    info = new ChartRenderingInfo();

                    if (mode == RenderingMode.SVG) {

                        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = null;
                        try {
                            docBuilder = docBuilderFactory.newDocumentBuilder();
                        } catch (ParserConfigurationException e1) {
                            throw new RuntimeException(e1);
                        }//from  w  ww .  j a  v a2  s.  c o m
                        Document document = docBuilder.newDocument();
                        Element svgelem = document.createElement("svg");
                        document.appendChild(svgelem);

                        // Create an instance of the SVG Generator
                        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

                        // draw the chart in the SVG generator

                        chart.draw(svgGenerator, new Rectangle(widht, height), info);
                        Element el = svgGenerator.getRoot();
                        el.setAttributeNS(null, "viewBox", "0 0 " + widht + " " + height + "");
                        el.setAttributeNS(null, "style", "width:100%;height:100%;");
                        el.setAttributeNS(null, "preserveAspectRatio", getSvgAspectRatio());

                        // Write svg to buffer
                        ByteArrayOutputStream baoutputStream = new ByteArrayOutputStream();
                        Writer out;
                        try {
                            OutputStream outputStream = gzipEnabled ? new GZIPOutputStream(baoutputStream)
                                    : baoutputStream;
                            out = new OutputStreamWriter(outputStream, "UTF-8");
                            /*
                             * don't use css, FF3 can'd deal with the result
                             * perfectly: wrong font sizes
                             */
                            boolean useCSS = false;
                            svgGenerator.stream(el, out, useCSS, false);
                            outputStream.flush();
                            outputStream.close();
                            bytestream = new ByteArrayInputStream(baoutputStream.toByteArray());
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (SVGGraphics2DIOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        // Draw png to bytestream
                        try {

                            byte[] bytes = ChartUtilities.encodeAsPNG(chart.createBufferedImage(widht, height));
                            bytestream = new ByteArrayInputStream(bytes);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }

                } else {
                    bytestream.reset();
                }
                return bytestream;
            }

            public Application getApplication() {
                return JFreeChartWrapper.this.getApplication();
            }

            public int getBufferSize() {
                if (getByteStream() != null) {
                    return getByteStream().available();
                } else {
                    return 0;
                }
            }

            public long getCacheTime() {
                return 0;
            }

            public String getFilename() {
                if (mode == RenderingMode.PNG) {
                    return "graph.png";
                } else {
                    return gzipEnabled ? "graph.svgz" : "graph.svg";
                }
            }

            public DownloadStream getStream() {
                DownloadStream downloadStream = new DownloadStream(getByteStream(), getMIMEType(),
                        getFilename());
                if (gzipEnabled && mode == RenderingMode.SVG) {
                    downloadStream.setParameter("Content-Encoding", "gzip");
                }
                return downloadStream;
            }

            public String getMIMEType() {
                if (mode == RenderingMode.PNG) {
                    return "image/png";
                } else {
                    return "image/svg+xml";
                }
            }
        };
    }
    return res;
}

From source file:org.opennms.netmgt.charts.ChartUtils.java

/**
 * Helper method that returns the JFreeChart as a PNG byte array.
 *
 * @param chartName a {@link java.lang.String} object.
 * @return a byte array//from   w  w  w.  j ava 2  s  .  c  om
 * @throws org.exolab.castor.xml.MarshalException if any.
 * @throws org.exolab.castor.xml.ValidationException if any.
 * @throws java.io.IOException if any.
 * @throws java.sql.SQLException if any.
 */
public static byte[] getBarChartAsPNGByteArray(String chartName)
        throws MarshalException, ValidationException, IOException, SQLException {
    BarChart chartConfig = getBarChartConfigByName(chartName);
    JFreeChart chart = getBarChart(chartName);
    ImageSize imageSize = chartConfig.getImageSize();
    int hzPixels;
    int vtPixels;

    if (imageSize == null) {
        hzPixels = 400;
        vtPixels = 400;
    } else {
        hzPixels = imageSize.getHzSize().getPixels();
        vtPixels = imageSize.getVtSize().getPixels();
    }
    return ChartUtilities.encodeAsPNG(chart.createBufferedImage(hzPixels, vtPixels));
}