Example usage for org.jfree.chart JFreeChart createBufferedImage

List of usage examples for org.jfree.chart JFreeChart createBufferedImage

Introduction

In this page you can find the example usage for org.jfree.chart JFreeChart createBufferedImage.

Prototype

public BufferedImage createBufferedImage(int width, int height) 

Source Link

Document

Creates and returns a buffered image into which the chart has been drawn.

Usage

From source file:ch.ksfx.web.services.chart.ObservationChartGenerator.java

public BufferedImage renderChart(JFreeChart jFreeChart, Integer width, Integer height) {
    jFreeChart.setBackgroundPaint(Color.white);

    System.out.println("[GRAPH] Creating buffered image");
    BufferedImage bi = jFreeChart.createBufferedImage(width, height);
    System.out.println("[GRAPH] Finished Creating buffered image");

    return bi;//  w  w w. java2 s  .co m
}

From source file:net.sf.jooreports.web.samples.SalesReportGenerator.java

private RenderedImage createChart(Object model) {
    List lines = (List) ((Map) model).get("lines");
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (Iterator it = lines.iterator(); it.hasNext();) {
        ReportLine line = (ReportLine) it.next();
        dataset.addValue(line.getValue(), "sales", line.getMonth());
    }//from   ww w. j  ava2  s  . co m
    JFreeChart chart = ChartFactory.createBarChart("Monthly Sales", "Month", "Sales", dataset,
            PlotOrientation.VERTICAL, false, false, false);
    chart.setTitle((String) null);
    chart.setBackgroundPaint(Color.white);
    CategoryPlot plot = chart.getCategoryPlot();
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    GradientPaint paint = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, new Color(0, 0, 64));
    renderer.setSeriesPaint(0, paint);
    BufferedImage image = chart.createBufferedImage(400, 300);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        ImageIO.write(image, "png", outputStream);
    } catch (IOException ioException) {
        throw new RuntimeException("should never happen: " + ioException.getMessage());
    }
    return image;
}

From source file:dinamica.ChartOutput.java

public void print(GenericTransaction t) throws Throwable {

    //get chart parameters
    Recordset chartinfo = t.getRecordset("chartinfo");

    //get chart data
    String id = chartinfo.getString("data");
    Recordset data = (Recordset) getSession().getAttribute(id);
    if (data == null)
        throw new Throwable(
                "Invalid Recordset ID:" + id + " - The session does not contain an attribute with this ID.");

    //general chart params
    Integer width = (Integer) chartinfo.getValue("width");
    Integer height = (Integer) chartinfo.getValue("height");

    //load chart plugin
    String plugin = (String) chartinfo.getValue("chart-plugin");
    AbstractChartPlugin obj = (AbstractChartPlugin) Thread.currentThread().getContextClassLoader()
            .loadClass(plugin).newInstance();

    JFreeChart chart = obj.getChart(chartinfo, data);

    //set gradient
    chart.setBackgroundPaint(getGradient());

    //set border and legend params
    chart.setBorderPaint(Color.LIGHT_GRAY);
    chart.setBorderVisible(true);/*from   w  w  w. j  a v a  2  s  .c  o m*/
    if (chart.getLegend() != null) {
        chart.getLegend().setBorder(0.2, 0.2, 0.2, 0.2);
        chart.getLegend().setPadding(5, 5, 5, 5);
        chart.getLegend().setMargin(4, 5, 4, 4);
    }

    //render chart in memory
    BufferedImage img = chart.createBufferedImage(width.intValue(), height.intValue());
    ByteArrayOutputStream b = new ByteArrayOutputStream(32768);

    //encode as PNG
    ImageIO.write(img, "png", b);

    //send bitmap via servlet output
    byte image[] = b.toByteArray();
    getResponse().setContentType("image/png");
    getResponse().setContentLength(image.length);
    OutputStream out = getResponse().getOutputStream();
    out.write(image);
    out.close();

    //save image bytes in session attribute if requested
    if (chartinfo.containsField("session")) {
        String session = chartinfo.getString("session");
        if (session != null && session.equals("true"))
            getSession().setAttribute(chartinfo.getString("image-id"), image);
    }

}

From source file:org.adempiere.webui.dashboard.CalendarWindow.java

private void syncModel() {
    Hashtable<String, BigDecimal> ht = new Hashtable<String, BigDecimal>();

    List<?> list = calendars.getModel().get(calendars.getBeginDate(), calendars.getEndDate(), null);
    int size = list.size();
    for (Iterator<?> it = list.iterator(); it.hasNext();) {
        String key = ((ADCalendarEvent) it.next()).getR_RequestType_ID() + "";

        if (!ht.containsKey(key))
            ht.put(key, BigDecimal.ONE);
        else {// ww  w  .j a va 2 s .c  o  m
            BigDecimal value = ht.get(key);
            ht.put(key, value.add(BigDecimal.ONE));
        }
    }

    Hashtable<Object, String> htTypes = new Hashtable<Object, String>();
    for (int i = 0; i < lbxRequestTypes.getItemCount(); i++) {
        Listitem li = lbxRequestTypes.getItemAtIndex(i);
        if (li != null && li.getValue() != null)
            htTypes.put(li.getValue(), li.getLabel());
    }

    DefaultPieDataset pieDataset = new DefaultPieDataset();
    Enumeration<?> keys = ht.keys();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        BigDecimal value = ht.get(key);
        String name = (String) htTypes.get(key);
        pieDataset.setValue(name == null ? "" : name,
                new Double(size > 0 ? value.doubleValue() / size * 100 : 0));
    }

    JFreeChart chart = ChartFactory.createPieChart3D(Msg.getMsg(Env.getCtx(), "EventsAnalysis"), pieDataset,
            true, true, true);
    PiePlot3D plot = (PiePlot3D) chart.getPlot();
    plot.setForegroundAlpha(0.5f);
    BufferedImage bi = chart.createBufferedImage(600, 250);
    try {
        byte[] bytes = EncoderUtil.encode(bi, ImageFormat.PNG, true);
        AImage image = new AImage("Pie Chart", bytes);
        myChart.setContent(image);
    } catch (IOException e) {
        e.printStackTrace();
    }
    htTypes = null;
    ht = null;
}

From source file:logica_controladores.controlador_estadistica.java

public static void grafica_orden(JPanel panel_grafica_orden, Inventario inventario, JLabel lbLinea) {
    XYSeries serie = null;/*from  w  w  w.  jav a 2s. com*/
    XYSeries serie_2 = null;

    JFreeChart linea;

    serie = new XYSeries("graficas relacion gastos-orden");
    Gasto gasto_minimo = valor_minimo(inventario);
    Gasto gasto_max = valor_maximo(inventario);
    for (int i = 0; i < inventario.getGastos().size(); i = i + inventario.getReorden_max()) {
        serie.add(inventario.getGastos().get(i).getOrden_inicial(), inventario.getGastos().get(i).getGastos());
    }
    serie_2 = new XYSeries("graficas relacion gastos-reorden");

    for (int i = 0; i < inventario.getGastos().size(); i = i + inventario.getOrden_max()) {
        serie_2.add(inventario.getGastos().get(i).getReorden(), inventario.getGastos().get(i).getGastos());
    }
    final XYSeriesCollection datos = new XYSeriesCollection();
    datos.addSeries(serie);
    datos.addSeries(serie_2);

    linea = ChartFactory.createXYLineChart(
            "grafica representativa de ordenes por corrida, gasto_minimo(orden: "
                    + gasto_minimo.getOrden_inicial() + "reorden: " + gasto_minimo.getReorden() + ")= "
                    + gasto_minimo.getGastos(),
            "rango", "gastos", datos, PlotOrientation.VERTICAL, true, true, true);
    final XYPlot plot = (XYPlot) linea.getPlot();
    final NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    configurarDomainAxis(domainAxis, inventario);
    configurarRangeAxis(rangeAxis, gasto_minimo.getGastos(), gasto_max.getGastos());
    BufferedImage graficoLinea = linea.createBufferedImage(600, 280);
    lbLinea.setSize(panel_grafica_orden.getSize());
    lbLinea.setIcon(new ImageIcon(graficoLinea));
    panel_grafica_orden.updateUI();
}

From source file:dinamica.SyncChartOutput.java

public void print(GenericTransaction t) throws Throwable {

    //get chart parameters
    Recordset chartinfo = t.getRecordset("chartinfo");

    //get chart data
    String id = chartinfo.getString("data");
    Recordset data = (Recordset) getSession().getAttribute(id);
    if (data == null)
        throw new Throwable(
                "Invalid Recordset ID:" + id + " - The session does not contain an attribute with this ID.");

    //general chart params
    Integer width = (Integer) chartinfo.getValue("width");
    Integer height = (Integer) chartinfo.getValue("height");

    //load chart plugin
    String plugin = (String) chartinfo.getValue("chart-plugin");
    AbstractChartPlugin obj = (AbstractChartPlugin) Thread.currentThread().getContextClassLoader()
            .loadClass(plugin).newInstance();

    JFreeChart chart = null;
    synchronized (data) {
        chart = obj.getChart(chartinfo, data);
    }/*from  w  w  w  . ja  va 2s. co  m*/

    //set gradient
    chart.setBackgroundPaint(getGradient());

    //set border and legend params
    chart.setBorderPaint(Color.LIGHT_GRAY);
    chart.setBorderVisible(true);
    if (chart.getLegend() != null) {
        chart.getLegend().setBorder(0.2, 0.2, 0.2, 0.2);
        chart.getLegend().setPadding(5, 5, 5, 5);
        chart.getLegend().setMargin(4, 5, 4, 4);
    }

    //render chart in memory
    BufferedImage img = chart.createBufferedImage(width.intValue(), height.intValue());
    ByteArrayOutputStream b = new ByteArrayOutputStream(32768);

    //encode as PNG
    ImageIO.write(img, "png", b);

    //send bitmap via servlet output
    byte image[] = b.toByteArray();
    getResponse().setContentType("image/png");
    getResponse().setContentLength(image.length);
    OutputStream out = getResponse().getOutputStream();
    out.write(image);
    out.close();

    //save image bytes in session attribute if requested
    if (chartinfo.containsField("session")) {
        String session = chartinfo.getString("session");
        if (session != null && session.equals("true"))
            getSession().setAttribute(chartinfo.getString("image-id"), image);
    }

}

From source file:org.jax.pubarray.server.restful.GraphingResource.java

/**
 * A RESTful interface for getting a graph image (well, we are cheating
 * by using an image key so it probably isn't true REST)
 * @param graphImageKey the graph image key
 * @param imageWidthPixles the image width in pixles
 * @param imageHeightPixles the image height in pixles
 * @return// w ww  . j  a  va  2 s . co m
 *          the image response
 */
@GET
@Path("/probe-intensity-graph-{graphImageKey}-" + "{imageWidthPixles}x{imageHeightPixles}.png")
public Response getProbeIntensityGraph(@PathParam("graphImageKey") String graphImageKey,
        @PathParam("imageWidthPixles") int imageWidthPixles,
        @PathParam("imageHeightPixles") int imageHeightPixles) {
    try {
        LOG.info("creating a graph image for key: " + graphImageKey);

        ProbeIntensityGraphConfiguration graphConfig = this.getProbeIntensityGraphConfiguration(graphImageKey);

        LOG.info("using graph configuration: " + graphConfig);

        JFreeChart graph = this.createProbeIntensityGraph(graphConfig);

        LOG.info("done creating graph, now rendering to an image of size: " + imageWidthPixles + "x"
                + imageHeightPixles);
        BufferedImage bi = graph.createBufferedImage(imageWidthPixles, imageHeightPixles);
        StreamingPNGOutput streamingImageOutput = new StreamingPNGOutput(bi);
        return Response.ok(streamingImageOutput).type("image/png").build();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, "failed to create probe intensity image", ex);
        return null;
    }
}

From source file:user.CreateChart.java

private ImageIcon barChart(CategoryDataset dataset, String name, String X, String Y) {

    final JFreeChart chart = ChartFactory.createBarChart(name, // chart title
            X, // domain axis label
            Y, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips?
            false // URLs?
    );//from ww  w. j  ava  2s.co m
    final CategoryPlot plot = chart.getCategoryPlot();
    final org.jfree.chart.axis.NumberAxis rangeAxis = (org.jfree.chart.axis.NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(org.jfree.chart.axis.NumberAxis.createIntegerTickUnits());

    ImageIcon ii = new ImageIcon(chart.createBufferedImage(592, 500));
    return ii;
}

From source file:com.elasticgrid.examples.video.components.WatchChart.java

public StreamResponse onChart(final int width, final int height, Object... rest)
        throws RemoteException, InterruptedException {
    String serviceID = (String) rest[2];
    String watchID = (String) rest[3];
    System.out.println("Service ID is: " + serviceID + ". Watch ID is: " + watchID);

    List<WatchDataSource> watches = ServiceLocator
            .getWatchDataSourcesByServiceID(ConfigUtil.createServiceID(serviceID));
    WatchDataSource watch = null;//from   w  w w .j ava2s  .  c o m
    for (WatchDataSource w : watches) {
        System.out.println("Testing with " + w.getID());
        if (w.getID().equals(watchID))
            watch = w;
    }
    if (watch == null)
        return null;

    TimeSeries s1 = new TimeSeries(watch.getID(), FixedMillisecond.class);
    for (Calculable calculable : watch.getCalculable())
        s1.add(new FixedMillisecond(calculable.getWhen()), calculable.getValue());

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(s1);

    final JFreeChart chart = ChartFactory.createTimeSeriesChart(watch.getID() + " Watch", // title
            "Date", // x-axis label
            "Value", // y-axis label
            dataset, // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );

    return new StreamResponse() {
        public String getContentType() {
            return "image/png";
        }

        public InputStream getStream() throws IOException {
            BufferedImage image = chart.createBufferedImage(width, height);
            ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
            ChartUtilities.writeBufferedImageAsPNG(byteArray, image);
            return new ByteArrayInputStream(byteArray.toByteArray());
        }

        public void prepareResponse(Response response) {
        }
    };
}

From source file:org.easyrec.controller.StatisticsController.java

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

    if (Security.isSignedIn(request)) {

        int tenant;
        int month;
        int year;
        boolean flot;

        String actionType = request.getParameter("actionType");
        try {//from   ww  w . j a  va 2 s . c  o m
            tenant = Integer.parseInt(request.getParameter("tenant"));
            month = Integer.parseInt(request.getParameter("month"));
            year = Integer.parseInt(request.getParameter("year"));
            flot = Integer.parseInt(request.getParameter("flot")) != 0;
        } catch (Exception e) {
            logger.warn(e);
            return null;
        }

        ModelAndView mav = new ModelAndView();
        XYSeriesCollection dataset = new XYSeriesCollection();
        FlotDataSet flotDataSet = new FlotDataSet();

        Calendar from = Calendar.getInstance();
        Calendar to = Calendar.getInstance();

        from.set(year, month, Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH), 0, 0, 0);
        to.set(year, month, from.getActualMaximum(Calendar.DAY_OF_MONTH), 23, 59, 59);

        Integer actionTypeId = null;
        Integer assocTypeId = null;

        if (!Strings.isNullOrEmpty(actionType)) {
            if ("CLICKS_ON_RECS".equals(actionType))
                assocTypeId = 1001;
            else if ("CLICKS_ON_CHARTS".equals(actionType))
                assocTypeId = 998;
            else
                actionTypeId = typeMappingService.getIdOfActionType(tenant, actionType);
        }

        HashMap<Integer, HashMap<Integer, Integer>> actionBundleMap = statisticsDAO.getActionBundleMap(tenant,
                from.getTimeInMillis(), to.getTimeInMillis(), actionTypeId, assocTypeId);

        Iterator<Integer> iterator = actionBundleMap.keySet().iterator();

        while (iterator.hasNext()) {
            actionTypeId = iterator.next();
            if (actionTypeId == 1001)
                actionType = "clicks on recommendations";
            else if (actionTypeId == 998)
                actionType = "clicks on rankings";
            else
                actionType = typeMappingService.getActionTypeById(tenant, actionTypeId).toLowerCase()
                        + " actions";

            XYSeries xySeries = new XYSeries(actionType);
            FlotSeries flotSeries = new FlotSeries();
            flotSeries.setTitle(actionType);

            for (int i = 1; i <= 31; i++) {
                Integer y = actionBundleMap.get(actionTypeId).get(i);
                xySeries.add(i, y != null ? y : 0);
                flotSeries.add(i, y != null ? y : 0);
            }
            //mav.addObject("data",flotDataSet.toString());

            dataset.addSeries(xySeries);
            flotDataSet.add(flotSeries);
        }

        // create datapoints that are rendered in the clients browser
        // return array or html side that renders array
        if (flot) {
            boolean onlyData = (ServletUtils.getSafeParameter(request, "onlyData", 0) != 0);
            if (onlyData) {
                mav.setViewName("flot/dataOutput");
            } else {
                mav.setViewName("flot/flotPlot");
            }
            mav.addObject("data", flotDataSet.toString());
            mav.addObject("flotDataSet", flotDataSet.getData());
            mav.addObject("noActions", flotDataSet.getData().isEmpty());
            return mav;

            // create a png
        } else {
            JFreeChart action_chart = ChartFactory.createXYLineChart("", "actions", "days", dataset,
                    PlotOrientation.VERTICAL, true, // show legend
                    true, // show tooltips
                    false); // show urls

            XYPlot plot = action_chart.getXYPlot();

            ValueAxis axis = plot.getDomainAxis();
            axis.setRange(1, 31);
            plot.setDomainAxis(axis);

            BufferedImage bi = action_chart.createBufferedImage(300, 200);

            byte[] bytes = ChartUtilities.encodeAsPNG(bi);

            if (bytes != null & !flot) {
                OutputStream os = response.getOutputStream();
                response.setContentType("image/png");
                response.setContentLength(bytes.length);
                os.write(bytes);
                os.close();
            }
        }
        return null;

    } else {
        return Security.redirectHome(request, response);
    }

}