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:ch.bfh.lca._15h.server.exporter.ExportHandler.java

/**
 * Saves the Chart to a JPG on a specific Filename
 * @param chart JFreeChart Chart./*w ww .  j  a v a 2s .c  o  m*/
 * @param fileName Full Path of File
 * @param width Width of image
 * @param height height of image
 * @return
 * @throws IOException 
 */
private String saveChartToJPG(final JFreeChart chart, String fileName, final int width, final int height)
        throws IOException {
    String result = null;

    if (chart != null) {
        if (fileName == null) {
            final String chartTitle = chart.getTitle().getText();
            if (chartTitle != null) {
                fileName = chartTitle;
            } else {
                fileName = "chart";
            }
        }
        result = fileName + ".jpg";
        ChartUtilities.saveChartAsJPEG(new File(result), chart, width, height);
    } //else: input unavailable

    return result;
}

From source file:sipl.recursos.Graficar.java

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

From source file:org.lmn.fc.common.datatranslators.DataExporter.java

/***********************************************************************************************
 * exportChart().//from ww w.  j a v a 2 s.  c  om
 * This variant uses a fully specified filename.
 *
 * @param dao
 * @param chartui
 * @param metadatalist
 * @param fullfilename
 * @param type
 * @param width
 * @param height
 * @param log
 * @param clock
 * @param verbose
 *
 * @return boolean
 */

public static boolean exportChartUsingFilename(final ObservatoryInstrumentDAOInterface dao,
        final ChartUIComponentPlugin chartui, final List<Metadata> metadatalist, final String fullfilename,
        final String type, final int width, final int height, final Vector<Vector> log,
        final ObservatoryClockInterface clock, final boolean verbose) {
    final String SOURCE = "DataExporter.exportChartUsingFilename() ";
    final boolean boolDebug;
    boolean boolSuccess;

    boolDebug = (LOADER_PROPERTIES.isChartDebug() || LOADER_PROPERTIES.isMetadataDebug()
            || LOADER_PROPERTIES.isStaribusDebug() || LOADER_PROPERTIES.isStarinetDebug());

    boolSuccess = false;

    // Let the User know the Chart must have data!
    if ((fullfilename != null) && (!EMPTY_STRING.equals(fullfilename)) && (type != null)
            && (!EMPTY_STRING.equals(type)) && (chartui != null) && (log != null) && (clock != null)) {
        try {
            final File file;

            file = new File(fullfilename);
            FileUtilities.overwriteFile(file);

            // Force the Chart to be generated, even if not visible
            // This calls ChartHelper.associateChartUIWithDAO()
            chartui.refreshChart(dao, true, SOURCE);

            if ((chartui.getChartPanel() != null) && (chartui.getChartPanel().getChart() != null)) {
                if (FileUtilities.jpg.equalsIgnoreCase(type)) {
                    LOGGER.debug(boolDebug, SOURCE + "writing [file " + file.getAbsolutePath() + "] [width="
                            + width + "] [height" + height + "]");
                    ChartUtilities.saveChartAsJPEG(file, chartui.getChartPanel().getChart(), width, height);
                    boolSuccess = true;

                    if (verbose) {
                        SimpleEventLogUIComponent.logEvent(
                                log, EventStatus.INFO, METADATA_TARGET_CHART + METADATA_ACTION_EXPORT
                                        + METADATA_FILENAME + file.getAbsolutePath() + TERMINATOR,
                                SOURCE, clock);
                    }
                } else if (FileUtilities.png.equalsIgnoreCase(type)) {
                    LOGGER.debug(boolDebug, SOURCE + "writing [file " + file.getAbsolutePath() + "] [width="
                            + width + "] [height" + height + "]");
                    ChartUtilities.saveChartAsPNG(file, chartui.getChartPanel().getChart(), width, height);
                    boolSuccess = true;

                    if (verbose) {
                        SimpleEventLogUIComponent.logEvent(
                                log, EventStatus.INFO, METADATA_TARGET_CHART + METADATA_ACTION_EXPORT
                                        + METADATA_FILENAME + file.getAbsolutePath() + TERMINATOR,
                                SOURCE, clock);
                    }
                } else {
                    SimpleEventLogUIComponent
                            .logEvent(
                                    log, EventStatus.FATAL, METADATA_TARGET_CHART + METADATA_ACTION_EXPORT
                                            + METADATA_RESULT + ERROR_INVALID_FORMAT + TERMINATOR,
                                    SOURCE, clock);
                }
            }
        }

        catch (SecurityException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_CHART + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_ACCESS_DENIED
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }

        catch (FileNotFoundException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_CHART + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_FILE_NOT_FOUND
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }

        catch (IOException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_CHART + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_FILE_SAVE
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }
    } else {
        //            System.out.println("FILENAME=" + ((fullfilename != null) && (!EMPTY_STRING.equals(fullfilename))));
        //            System.out.println("TYPE=" + ((type != null) && (!EMPTY_STRING.equals(type))));
        //            System.out.println("CHART=" + (chart != null));
        //            System.out.println("LOG=" + (log != null));
        //            System.out.println("CLOCK=" + (clock != null));
        SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                METADATA_TARGET_CHART + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_CHART + TERMINATOR,
                SOURCE, clock);
    }

    return (boolSuccess);
}

From source file:sipl.recursos.Graficar.java

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

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

/**
 * creates a line chart with all booked hours of a specific employee
 * @param employeeID ID of the employee for which a chart should be created
 *///  w  w  w .  j a va 2 s.  co  m
public void createChart(int employeeID) {

    // get dataset
    XYSeriesCollection dataset;
    dataset = createDataset(employeeID);

    // create chart
    JFreeChart xylineChart = ChartFactory.createXYLineChart("", "Month", "Hours", dataset,
            PlotOrientation.VERTICAL, true, true, false);

    // set color of chart
    XYPlot plot = xylineChart.getXYPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    renderer.setSeriesPaint(0, new Color(0, 101, 166));
    renderer.setSeriesPaint(1, new Color(0, 62, 102));
    plot.setRenderer(renderer);

    // set size of the chart and save it as JPEG
    int width = 1200;
    int height = 600;
    File lineChart = new File(
            path + "/Charts/EffortProject" + project.getID() + "_Employee" + employeeID + ".jpg");
    try {
        ChartUtilities.saveChartAsJPEG(lineChart, xylineChart, width, height);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Questao3.java

/**
 * Metodo cria e exibe o grfico da media dos pixels das imagens resultantes
 * @throws IOException// ww w. j a va  2s. c  om
 */
public void criaGrafico() throws IOException {
    CategoryDataset cds = createDataset();
    String titulo = "Mdia da Primeira linha de pixels";
    String eixoy = "Valores";
    String txt_legenda = "Pixels";
    boolean legenda = true;
    boolean tooltips = true;
    boolean urls = true;
    JFreeChart graf = ChartFactory.createLineChart(titulo, txt_legenda, eixoy, cds);
    File lineChart = new File("grafico.jpeg");
    ChartUtilities.saveChartAsJPEG(lineChart, graf, 512, 256);
    showResult("grafico.jpeg");
}

From source file:it.marcoberri.mbmeteo.action.chart.Get.java

/**
 * Processes requests for both HTTP/* w  ww .ja  va  2 s.c o  m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);
    final String from = Default.toString(params.get("from") + " 00:00:00", "1970-01-01 00:00:00");
    final String to = Default.toString(params.get("to") + " 23:59:00", "2030-01-01 23:59:00");
    final String field = Default.toString(params.get("field"), "outdoorTemperature");

    request.getSession().setAttribute("from", params.get("from"));
    request.getSession().setAttribute("to", params.get("to"));

    final String cacheKey = getCacheKey(params);

    if (cacheReadEnable) {
        final Query q = ds.find(Cache.class);
        q.filter("cacheKey", cacheKey).filter("servletName", this.getClass().getName());

        final Cache c = (Cache) q.get();

        if (c == null) {
            log.info("cacheKey:" + cacheKey + " on servletName: " + this.getClass().getName() + " not found");
        }

        if (c != null) {
            log.debug("get file from cache id: " + c.getGridId());
            final GridFSDBFile imageForOutput = MongoConnectionHelper.getGridFS()
                    .findOne(new ObjectId(c.getGridId()));
            if (imageForOutput != null) {

                ds.save(c);

                try {
                    response.setHeader("Content-Length", "" + imageForOutput.getLength());
                    response.setHeader("Content-Disposition",
                            "inline; filename=\"" + imageForOutput.getFilename() + "\"");
                    final OutputStream out = response.getOutputStream();
                    final InputStream in = imageForOutput.getInputStream();
                    final byte[] content = new byte[(int) imageForOutput.getLength()];
                    in.read(content);
                    out.write(content);
                    in.close();
                    out.close();
                    return;
                } catch (final IOException e) {
                    log.error(e);
                }

            } else {
                log.error("file not in db");
            }
        }
    }

    final String titleChart = ChartEnumHelper.getByName(field).getTitle();
    final String umChart = ChartEnumHelper.getByName(field).getUm();
    final Query q = ds.createQuery(Meteolog.class);
    final Date dFrom = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", from);
    final Date dTo = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", to);

    q.disableValidation().filter("time >=", dFrom).filter("time <=", dTo);

    final List<Meteolog> meteoLogList = q.asList();
    final TimeSeries series = new TimeSeries(umChart);

    for (Meteolog m : meteoLogList) {
        final Millisecond t = new Millisecond(m.getTime());
        try {
            //violenza di una reflection
            final Method method = m.getClass().getMethod(ChartEnumHelper.getByName(field).getMethod());
            final Number n = (Number) method.invoke(m);
            series.add(t, n);
        } catch (final NoSuchMethodException ex) {
            log.error(ex);
        } catch (final InvocationTargetException ex) {
            log.error(ex);
        } catch (final IllegalAccessException ex) {
            log.error(ex);
        } catch (final SecurityException ex) {
            log.error(ex);
        }

    }

    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);

    final JFreeChart chart = ChartFactory.createTimeSeriesChart(titleChart, "", umChart, dataset, false, false,
            false);
    final XYPlot plot = (XYPlot) chart.getPlot();
    final DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy HH:mm"));
    axis.setVerticalTickLabels(true);

    if (field.toUpperCase().indexOf("PRESSURE") != -1) {
        plot.getRangeAxis().setRange(chartPressureMin, chartPressureMax);
    }

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart, dimx, dimy);

    try {

        if (cacheWriteEnable) {

            final GridFSInputFile gfsFile = MongoConnectionHelper.getGridFS().createFile(f);
            gfsFile.setFilename(f.getName());
            gfsFile.save();

            final Cache c = new Cache();
            c.setServletName(this.getClass().getName());
            c.setCacheKey(cacheKey);
            c.setGridId(gfsFile.getId().toString());

            ds.save(c);

        }

        response.setContentType("image/jpeg");
        response.setHeader("Content-Length", "" + f.length());
        response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
        final OutputStream out = response.getOutputStream();
        final FileInputStream in = new FileInputStream(f.toString());
        final int size = in.available();
        final byte[] content = new byte[size];
        in.read(content);
        out.write(content);
        in.close();
        out.close();
    } catch (final IOException e) {
        log.error(e);
    } finally {
        f.delete();
    }

}

From source file:org.graphstream.algorithm.measure.ChartMeasure.java

/**
 * Output some charts according to a set of parameters. Actually, only one
 * chart is supported. According to {@link PlotParameters#outputType}, plot
 * is displayed on screen or saved in a file.
 * /*from  w  w w.  j  a v  a  2s .c o m*/
 * @param params
 *            parameters used to plot
 * @param charts
 *            charts to output
 * @throws PlotException
 */
public static void outputPlot(PlotParameters params, JFreeChart... charts) throws PlotException {
    if (charts == null || charts.length == 0)
        throw new PlotException("no chart");

    if (charts.length > 1)
        throw new PlotException("multiple charts not yet supported");

    JFreeChart chart = charts[0];

    switch (params.outputType) {
    case SCREEN:
        ChartPanel panel = new ChartPanel(chart, params.width, params.height, params.width, params.height,
                params.width + 50, params.height + 50, true, true, true, true, true, true);

        JFrame frame = new JFrame(params.title);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);

        break;
    case JPEG:
        try {
            ChartUtilities.saveChartAsJPEG(new File(params.path), chart, params.width, params.height);
        } catch (IOException e) {
            throw new PlotException(e);
        }

        break;
    case PNG:
        try {
            ChartUtilities.saveChartAsPNG(new File(params.path), chart, params.width, params.height);
        } catch (IOException e) {
            throw new PlotException(e);
        }

        break;
    }

}

From source file:org.cytoscape.dyn.internal.graphMetrics.SaveChartDialog.java

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if (e.getSource() == cancelButton) {
        this.setVisible(false);
        this.dispose();
    } else if (e.getSource() == saveChartButton) {
        JFileChooser saveFileDialog = new JFileChooser();
        saveFileDialog//from   w w  w.  ja v  a 2  s.c  o m
                .addChoosableFileFilter(new ExtensionFileFilter(".jpeg", ".jpg", "Jpeg images (.jpeg, .jpg)"));
        saveFileDialog.addChoosableFileFilter(
                new ExtensionFileFilter(".png", "Portable Network Graphic images (.png)"));
        saveFileDialog
                .addChoosableFileFilter(new ExtensionFileFilter(".svg", "Scalable Vector Graphics (.svg)"));
        int save = saveFileDialog.showSaveDialog(this);
        if (save == JFileChooser.APPROVE_OPTION) {
            File file = saveFileDialog.getSelectedFile();
            int width = ((SpinnerNumberModel) widthSpinner.getModel()).getNumber().intValue();
            int height = ((SpinnerNumberModel) heightSpinner.getModel()).getNumber().intValue();

            ExtensionFileFilter filter = null;
            try {
                filter = (ExtensionFileFilter) saveFileDialog.getFileFilter();
                if (!filter.hasExtension(file)) {
                    file = filter.appendExtension(file);
                }
            } catch (ClassCastException ex) {
                // Try to infer the type of file by its extension
                FileFilter[] filters = saveFileDialog.getChoosableFileFilters();
                for (int i = 0; i < filters.length; ++i) {
                    if (filters[i] instanceof ExtensionFileFilter) {
                        filter = (ExtensionFileFilter) filters[i];
                        if (filter.hasExtension(file)) {
                            break;
                        }
                        filter = null;
                    }
                }

                if (filter == null) {
                    // Could not infer the type
                    JOptionPane.showMessageDialog(null,
                            "File type not specified!\nWhen giving file name, please also select one of the supported file types.",
                            "Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            // Save the chart to the specified file name
            try {
                String ext = filter.getExtension();
                if (ext.equals("jpeg")) {
                    ChartUtilities.saveChartAsJPEG(file, chart, width, height);
                } else if (ext.equals("png")) {
                    ChartUtilities.saveChartAsPNG(file, chart, width, height);
                } else {
                    VectorGraphics graphics = new SVGGraphics2D(file, new Dimension(width, height));
                    graphics.startExport();
                    chart.draw(graphics, new Rectangle2D.Double(0, 0, width, height));
                    graphics.endExport();
                }
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "An error occurred while creating or writing to the file.",
                        "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            this.setVisible(false);
            this.dispose();
        } else if (save == JFileChooser.ERROR_OPTION) {
            JOptionPane.showMessageDialog(null, "An error occurred while initializing the window.", "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:sipl.recursos.Graficar.java

public void PrestamosY_Barra(int[][] values, int n, String direccion, String tiempo, String titulo) {
    //Crear el dataset...
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (int i = 1; i < n; i++) {
        if (n != 0) {
            dataset.addValue(values[i][1], "Cantidad de Prstamos", "" + values[i][0]);
        }/* w  w  w . j  a v  a2 s.  com*/
    }
    JFreeChart chart = ChartFactory.createBarChart(titulo, tiempo, "Cantidad", dataset,
            PlotOrientation.VERTICAL, true, true, false);
    try {
        ChartUtilities.saveChartAsJPEG(new File(direccion), chart, 500, 500);
    } catch (IOException e) {
        System.err.println("Error al crear al chart.");
    }
}