Example usage for org.jfree.chart ChartUtilities saveChartAsJPEG

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

Introduction

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

Prototype

public static void saveChartAsJPEG(File file, JFreeChart chart, int width, int height) throws IOException 

Source Link

Document

Saves a chart to a file in JPEG format.

Usage

From source file:sipl.recursos.Graficar.java

public void Multas(int[] values, int[] fecha, int n, String direccion, String tiempo, String titulo) {
    try {/*from   ww w .j  a v a  2 s.  c om*/
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for (int j = 0; j < n; j++) {
            dataset.addValue(values[j], "Cantidad de Multas", "" + fecha[j]);
        }
        JFreeChart chart = ChartFactory.createLineChart(titulo, tiempo, "Cantidad", dataset,
                PlotOrientation.VERTICAL, true, true, true);
        try {
            ChartUtilities.saveChartAsJPEG(new File(direccion), chart, 700, 500);
        } catch (IOException e) {
            System.out.println("Error al abrir el archivo");
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:com.bbn.c2s2.pint.testdata.chart.ScatterPlot.java

public void toJpgFile(String fileName, int xSize, int ySize) throws IOException {
    ChartUtilities.saveChartAsJPEG(new File(fileName), chart, xSize, ySize);
}

From source file:edu.gcsc.vrl.jfreechart.JFExport.java

/**
 * Export jfreechart to image format. File must have an extension like jpg,
 * png, pdf, svg, eps. Otherwise export will fail.
 *
 * @param file Destination Filedescriptor
 * @param chart JFreechart//  ww  w  .  jav  a  2s.  c o m
 * @throws Exception
 */
public boolean export(File file, JFreeChart chart) throws Exception {

    /*Get extension from file - File must have one extension of
     jpg,png,pdf,svg,eps. Otherwise the export will fail.
     */
    String ext = JFUtils.getExtension(file);

    //  TODO - Make x,y variable
    int x, y;
    // Set size for image (jpg)
    x = 550;
    y = 470;

    int found = 0;

    // JPEG
    if (ext.equalsIgnoreCase("jpg")) {
        ChartUtilities.saveChartAsJPEG(file, chart, x, y);
        found++;
    }
    // PNG
    if (ext.equalsIgnoreCase("png")) {
        ChartUtilities.saveChartAsPNG(file, chart, x, y);
        found++;
    }

    // PDF
    if (ext.equalsIgnoreCase("pdf")) {

        //JRAbstractRenderer jfcRenderer = new JFreeChartRenderer(chart);
        // Use here size of r2d2 (see below, Rectangel replaced by Rectangle2D !)
        Rectangle pagesize = new Rectangle(x, y);

        Document document = new Document(pagesize, 50, 50, 50, 50);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(x, y);

        Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper());

        // Draw doesn't works with Rectangle argument - use rectangle2D instead !
        //chart.draw(g2, (java.awt.geom.Rectangle2D) new Rectangle(x,y));
        Rectangle2D r2d2 = new Rectangle2D.Double(0, 0, x, y);
        chart.draw(g2, r2d2);

        g2.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();

        found++;

    }

    // SVG
    if (ext.equalsIgnoreCase("svg")) {
        // When exporting to SVG don't forget this VERY important line:
        // svgGenerator.setSVGCanvasSize(new Dimension(width, height));
        // Otherwise renderers will not know the size of the image. It will be drawn to the correct rectangle, but the image will not have a correct default siz
        // Get a DOMImplementation
        DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
        org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
        //chart.draw(svgGenerator,new Rectangle(x,y));
        chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, x, y));

        boolean useCSS = true; // we want to use CSS style attribute

        Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        svgGenerator.stream(out, useCSS);
        out.close();
        found++;
    }

    if (ext.equalsIgnoreCase("eps")) {

        //Graphics2D g = new EpsGraphics2D();
        FileOutputStream out = new FileOutputStream(file);
        //Writer out=new FileWriter(file);
        Graphics2D g = new EpsGraphics(file.getName(), out, 0, 0, x, y, ColorMode.COLOR_RGB);

        chart.draw(g, new Rectangle2D.Double(0, 0, x, y));
        //Writer out=new FileWriter(file);
        out.write(g.toString().getBytes());
        out.close();
        found++;
    }

    if (found == 0) {
        throw new IllegalArgumentException("File format '" + ext + "' not supported!");
    }

    return true;

}

From source file:ch.zhaw.init.walj.projectmanagement.util.chart.GanttChart.java

/**
 * creates a gantt chart with all workpackages and tasks
 * @throws NumberFormatException/*  w ww . j av a  2  s .  c o  m*/
 */
public void createChart() throws NumberFormatException, IOException {

    // get data
    IntervalCategoryDataset dataset = createDataset();

    // create chart
    JFreeChart chart = ChartFactory.createGanttChart("", // chart title
            "", // domain axis label
            "", // range axis label
            dataset, // data
            false, // include legend
            false, // tooltips
            false // urls
    );

    // set white background
    chart.setBackgroundPaint(new Color(255, 255, 255));

    // set color of bars
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    CategoryItemRenderer renderer = plot.getRenderer();
    renderer.setSeriesPaint(0, new Color(0, 62, 102));

    // set size of the chart
    int width = 1200;
    int height = (40 * nbrOfObjects) + 200;

    // save picture as JPEG
    File gantChart = new File(path + "/Charts/GanttProject" + project.getID() + ".jpg");
    ChartUtilities.saveChartAsJPEG(gantChart, chart, width, height);
}

From source file:com.itemanalysis.jmetrik.graph.irt.IrtPlotPanel.java

public void savePlots(String path) throws IOException {
    File dir = new File(path);
    if (!dir.exists())
        dir.mkdirs();/*  w  w w. j  a  v  a2 s  . c  o m*/
    for (String s : charts.keySet()) {
        JFreeChart c = charts.get(s);
        ChartUtilities.saveChartAsJPEG(new File(dir.getAbsolutePath() + "/" + s + ".jpg"), c, width, height);
    }
}

From source file:br.com.ant.system.util.ChartUtil.java

public void createCaminhoPercorrido(EstatisticaColetor estatisticaColetor) {

    // Create a simple XY chart

    JFrame frame = new JFrame();

    // Add the series to your data set
    XYSeriesCollection dataset = new XYSeriesCollection();

    Map<Cidade, List<Estatistica>> mapformigasEstatisticas = new HashMap<Cidade, List<Estatistica>>();
    for (Estatistica e : estatisticaColetor.getEstatisticas()) {
        if (mapformigasEstatisticas.containsKey(e.getCidadeInicial())) {
            mapformigasEstatisticas.get(e.getCidadeInicial()).add(e);
        } else {//from  ww w  .  j  a  v a2 s .c  o  m
            List<Estatistica> lista = new ArrayList<Estatistica>();
            lista.add(e);

            mapformigasEstatisticas.put(e.getCidadeInicial(), lista);
        }
    }

    Set<Cidade> cidades = mapformigasEstatisticas.keySet();
    for (Cidade c : cidades) {
        // for (int i = 0; i < 2; i++) {
        List<Estatistica> list = (List<Estatistica>) mapformigasEstatisticas.get(c);

        XYSeries series = new XYSeries(c.getNome());
        dataset.addSeries(series);

        for (Estatistica e : list) {
            if (e.getFormigaId() == 1) {
                series.add(e.getIteracao(), e.getDistanciaPercorrida());
            }
        }
    }

    // Generate the graph
    JFreeChart chart = ChartFactory.createXYLineChart("", "Iterao", "Distancia (Km)", dataset,
            PlotOrientation.VERTICAL, true, true, false);
    frame.getContentPane().add(new ChartPanel(chart));

    frame.setPreferredSize(new Dimension(600, 600));
    frame.setMinimumSize(new Dimension(600, 600));
    frame.setMaximumSize(new Dimension(600, 600));
    frame.setVisible(true);

    try {
        ChartUtilities.saveChartAsJPEG(new File("chart.jpg"), chart, 500, 300);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }
}

From source file:de.fhbingen.wbs.wpOverview.tabs.APCalendarPanel.java

/**
 * Initialize the work package calendar panel inclusive the listeners.
 *//* ww w. jav  a 2 s  .  co  m*/
private void init() {
    List<Workpackage> userWp = new ArrayList<Workpackage>(WpManager.getUserWp(WPOverview.getUser()));

    Collections.sort(userWp, new APLevelComparator());

    dataset = createDataset(userWp);
    chart = createChart(dataset);

    final ChartPanel chartPanel = new ChartPanel(chart);

    final JPopupMenu popup = new JPopupMenu();
    JMenuItem miSave = new JMenuItem(LocalizedStrings.getButton().save(LocalizedStrings.getWbs().timeLine()));
    miSave.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(final ActionEvent arg0) {

            JFileChooser chooser = new JFileChooser();
            chooser.setFileFilter(new ExtensionAndFolderFilter("jpg", "jpeg")); //NON-NLS
            chooser.setSelectedFile(new File("chart-" //NON-NLS
                    + System.currentTimeMillis() + ".jpg"));
            int returnVal = chooser.showSaveDialog(reference);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                try {
                    File outfile = chooser.getSelectedFile();
                    ChartUtilities.saveChartAsJPEG(outfile, chart, chartPanel.getWidth(),
                            chartPanel.getWidth());
                    Controller.showMessage(
                            LocalizedStrings.getMessages().timeLineSaved(outfile.getCanonicalPath()));
                } catch (IOException e) {
                    Controller.showError(LocalizedStrings.getErrorMessages().timeLineExportError());
                }
            }
        }

    });
    popup.add(miSave);

    chartPanel.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(final MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON3) {
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        }

    });
    chartPanel.setMinimumDrawHeight(50 + 15 * userWp.size());
    chartPanel.setMaximumDrawHeight(50 + 15 * userWp.size());
    chartPanel.setMaximumDrawWidth(9999);
    chartPanel.setPreferredSize(
            new Dimension((int) chartPanel.getPreferredSize().getWidth(), 50 + 15 * userWp.size()));

    chartPanel.setPopupMenu(null);

    this.setLayout(new BorderLayout());

    this.removeAll();

    JPanel panel = new JPanel();
    panel.setLayout(new GridBagLayout());
    GridBagConstraints constraints = new GridBagConstraints();
    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.weightx = 1;
    constraints.weighty = 1;
    constraints.anchor = GridBagConstraints.NORTHWEST;
    panel.add(chartPanel, constraints);

    panel.setBackground(Color.white);
    this.add(panel, BorderLayout.CENTER);

    GanttRenderer.setDefaultShadowsVisible(false);
    GanttRenderer.setDefaultBarPainter(new BarPainter() {

        @Override
        public void paintBar(final Graphics2D g, final BarRenderer arg1, final int row, final int col,
                final RectangularShape rect, final RectangleEdge arg5) {

            String wpName = (String) dataset.getColumnKey(col);
            int i = 0;
            int spaceCount = 0;
            while (wpName.charAt(i++) == ' ' && spaceCount < 17) {
                spaceCount++;
            }

            g.setColor(new Color(spaceCount * 15, spaceCount * 15, spaceCount * 15));
            g.fill(rect);
            g.setColor(Color.black);
            g.setStroke(new BasicStroke());
            g.draw(rect);
        }

        @Override
        public void paintBarShadow(final Graphics2D arg0, final BarRenderer arg1, final int arg2,
                final int arg3, final RectangularShape arg4, final RectangleEdge arg5, final boolean arg6) {

        }

    });

    ((CategoryPlot) chart.getPlot()).setRenderer(new GanttRenderer() {
        private static final long serialVersionUID = -6078915091070733812L;

        public void drawItem(final Graphics2D g2, final CategoryItemRendererState state,
                final Rectangle2D dataArea, final CategoryPlot plot, final CategoryAxis domainAxis,
                final ValueAxis rangeAxis, final CategoryDataset dataset, final int row, final int column,
                final int pass) {
            super.drawItem(g2, state, dataArea, plot, domainAxis, rangeAxis, dataset, row, column, pass);
        }
    });

}

From source file:com.sun.japex.ChartGenerator.java

public void generateDriverChart(String fileName) {
    try {//from w  ww.j a v  a 2 s  .  co  m
        JFreeChart chart = null;
        String chartType = _testSuite.getParam(Constants.CHART_TYPE);

        if (chartType.equalsIgnoreCase("barchart")) {
            chart = generateDriverBarChart();
        } else if (chartType.equalsIgnoreCase("scatterchart")) {
            chart = generateDriverScatterChart();
        } else if (chartType.equalsIgnoreCase("linechart")) {
            chart = generateDriverLineChart();
        } else {
            assert false;
        }

        chart.setAntiAlias(true);
        ChartUtilities.saveChartAsJPEG(new File(fileName), chart, _chartWidth, _chartHeight);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:ANNFileDetect.EncogTestClass.java

private void drawchart(TreeMap<Double, Integer> ht, String file, int minima) throws IOException {
    DefaultCategoryDataset ds = new DefaultCategoryDataset();
    //XYDataset xy = new XYDataset();
    /*/*  w  ww.  j  av a  2  s  .  c om*/
       * Enumeration<Double> e = ht.keys(); while (e.hasMoreElements()) {
       * Double tmp = e.nextElement(); //ds.addValue(ht.get(tmp), "Times",
       * tmp); if (ht.get(tmp) > 100) ds.addValue(ht.get(tmp), "Times", tmp);
       * }
       */
    for (Map.Entry<Double, Integer> entry : ht.entrySet()) {
        //ds.addValue(ht.get(tmp), "Times", tmp); 
        if (entry.getValue() > minima) {
            ds.addValue(entry.getValue(), "Times", entry.getKey());
        }
    }
    /*
     * while (e.hasMoreElements()) { Double tmp = e.nextElement();
     * //ds.addValue(ht.get(tmp), "Times", tmp); if (ht.get(tmp) > 100)
     * ds.addValue(ht.get(tmp), "Times", tmp); }
     */
    JFreeChart chart = ChartFactory.createBarChart(file, "quantity", "value", ds, PlotOrientation.VERTICAL,
            true, true, false);
    //JFreeChart chart = ChartFactory.createScatterPlot(file, "quantity", "value",ds, PlotOrientation.VERTICAL, true, true, false);
    String dlt = "/";
    String[] tmpfl = file.split(dlt);
    String crp = tmpfl[tmpfl.length - 1];
    String[] actfl = crp.split("\\.");
    ChartUtilities.saveChartAsJPEG(new File("/tmp/charts/" + actfl[1].toUpperCase() + actfl[0]), chart, 6000,
            1200);
    files++;
}

From source file:com.sun.japex.report.ReportGenerator.java

private void saveChart(JFreeChart chart, String fileName, int width, int height) {
    try {//from  w ww  . j ava 2 s . co m
        // Converts chart in JPEG file named [name].jpg
        File file = new File(_params.outputPath());
        if (!file.exists()) {
            file.mkdirs();
        }
        ChartUtilities.saveChartAsJPEG(new File(_params.outputPath() + FILE_SEP + fileName), chart, width,
                height);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}