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:Ventanas.VentanaVerGrafico.java

private void initGUI() {
    try {/*  w  w w  . ja v  a  2 s  . co  m*/
        this.setLayout(null);
        this.setIconImage(
                new ImageIcon(getClass().getClassLoader().getResource("Ventanas/is_a4af.gif")).getImage());
        this.setTitle("Grfica");
        this.setSize(705, 580);
        this.getContentPane().setBackground(new java.awt.Color(204, 230, 230));
        this.setLocationRelativeTo(null);
        this.setResizable(false);

        {
            CategoryDataset dataset = createCategoryDataset(((Vector) VentanaVerEstadisticas.datosEstadistica));
            JFreeChart chart = ChartFactory.createBarChart3D("Rendimiento de los operarios", "Operarios", "",
                    dataset, PlotOrientation.HORIZONTAL, true, true, false);
            chart.setBackgroundPaint(new Color(204, 230, 230));
            grafica = chart.createBufferedImage(700, 500);
            paint(grafica.getGraphics());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:de.mpg.escidoc.pubman.statistic_charts.StatisticChartServlet.java

public synchronized void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String numberOfMonthsString = request.getParameter(numberOfMonthsParameterName);
    if (numberOfMonthsString == null) {
        numberOfMonths = 12;/*from www.j a  v a 2s  . c  om*/
    } else {
        numberOfMonths = Integer.parseInt(numberOfMonthsString);
    }

    String lang = request.getParameter(languageParameterName);
    if (lang == null) {
        this.language = "en";
    } else {
        this.language = lang;
    }

    id = request.getParameter(idParameterName);
    type = request.getParameter(typeParameterName);

    try {

        CategoryDataset dataset = createDataset();
        JFreeChart chart = createChart(dataset);
        BufferedImage img = chart.createBufferedImage(630, 250);
        byte[] image = new KeypointPNGEncoderAdapter().encode(img);

        response.setContentType(CONTENT_TYPE);
        ServletOutputStream out = response.getOutputStream();
        out.write(image);
        out.flush();
        out.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:ImageProcessing.GrayscaleHistogram_GUI.java

public GrayscaleHistogram_GUI(Component callerComponent) {
    //callerComponent is used only to determine the position of this
    //frame when called.

    initComponents();/*from w w w  .  j av  a2 s . c  o m*/
    this.setLocationRelativeTo(callerComponent);

    //Determine chart width & height in display.
    int chartLabelHeight = sourceImageHistogram.getHeight();
    int chartLabelWidth = sourceImageHistogram.getWidth();

    //Get Grayscale value for every pixels from source & processed image.
    double[] sourceGrayValues = ImageProcessing.extractGrayColor(Main.getSourceImage());
    double[] processedGrayValues = ImageProcessing.extractGrayColor(Main.getProcessedImage());

    //Create two charts using the grayscale values.
    JFreeChart sourceChart = ImageProcessing.createHistogram(sourceGrayValues, Color.BLACK);
    JFreeChart processedChart = ImageProcessing.createHistogram(processedGrayValues, Color.BLACK);

    //Convert the charts to a BufferedImage for displaying.
    BufferedImage sourceChartImage = sourceChart.createBufferedImage(chartLabelWidth, chartLabelHeight);
    BufferedImage processedChartImage = processedChart.createBufferedImage(chartLabelWidth, chartLabelHeight);

    //Display the chart images.
    sourceImageHistogram.setIcon(new ImageIcon(sourceChartImage));
    processedImageHistogram.setIcon(new ImageIcon(processedChartImage));
}

From source file:org.drools.planner.benchmark.statistic.bestscore.BestScoreStatistic.java

private CharSequence writeGraphStatistic(File solverStatisticFilesDirectory, String baseName) {
    NumberAxis xAxis = new NumberAxis("Time millis spend");
    xAxis.setNumberFormatOverride(new MillisecondsSpendNumberFormat());
    NumberAxis yAxis = new NumberAxis("Score");
    yAxis.setAutoRangeIncludesZero(false);
    XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
    int seriesIndex = 0;
    for (Map.Entry<String, BestScoreStatisticListener> listenerEntry : bestScoreStatisticListenerMap
            .entrySet()) {// w  ww.  j  a  v  a  2  s  .c  om
        String configName = listenerEntry.getKey();
        XYSeries series = new XYSeries(configName);
        List<BestScoreStatisticPoint> statisticPointList = listenerEntry.getValue().getStatisticPointList();
        for (BestScoreStatisticPoint statisticPoint : statisticPointList) {
            long timeMillisSpend = statisticPoint.getTimeMillisSpend();
            Score score = statisticPoint.getScore();
            Double scoreGraphValue = scoreDefinition.translateScoreToGraphValue(score);
            if (scoreGraphValue != null) {
                series.add(timeMillisSpend, scoreGraphValue);
            }
        }
        XYSeriesCollection seriesCollection = new XYSeriesCollection();
        seriesCollection.addSeries(series);
        plot.setDataset(seriesIndex, seriesCollection);
        XYItemRenderer renderer;
        // No direct lines between 2 points
        renderer = new XYStepRenderer();
        if (statisticPointList.size() <= 1) {
            // Workaround for https://sourceforge.net/tracker/?func=detail&aid=3387330&group_id=15494&atid=115494
            renderer = new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES);
        }
        plot.setRenderer(seriesIndex, renderer);
        seriesIndex++;
    }
    plot.setOrientation(PlotOrientation.VERTICAL);
    JFreeChart chart = new JFreeChart(baseName + " best score statistic", JFreeChart.DEFAULT_TITLE_FONT, plot,
            true);
    BufferedImage chartImage = chart.createBufferedImage(1024, 768);
    File graphStatisticFile = new File(solverStatisticFilesDirectory, baseName + "BestScoreStatistic.png");
    OutputStream out = null;
    try {
        out = new FileOutputStream(graphStatisticFile);
        ImageIO.write(chartImage, "png", out);
    } catch (IOException e) {
        throw new IllegalArgumentException("Problem writing graphStatisticFile: " + graphStatisticFile, e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    return "  <img src=\"" + graphStatisticFile.getName() + "\"/>\n";
}

From source file:cmsc105_mp2.Panels.java

public void createGraph(Data d, float window, Double threshold) {
    XYSeries data = new XYSeries("data");
    double max = Double.MIN_VALUE;
    for (double num : d.plots) {
        if (max < num)
            max = num;/*w ww.j  av  a 2  s.  c om*/
    }
    max += 1;

    ArrayList<XYSeries> xy = new ArrayList();
    ArrayList<Integer> points = new ArrayList();

    for (int j = (int) (window / 2); j < d.plots.length - (window / 2); j++) {
        data.add(j, d.plots[j]);
        //System.out.println(points.size());
        if (d.plots[j] > threshold) {
            points.add(j);
        } else {
            if (points.size() >= window) {
                //System.out.println("MIN!");
                XYSeries series = new XYSeries("trend");
                for (int n : points) {
                    series.add(n, max);
                }
                xy.add(series);
            }
            points = new ArrayList();
        }
    }
    if (points.size() >= window) {
        XYSeries series = new XYSeries("trend");
        for (int n : points) {
            series.add(n, max);
        }
        xy.add(series);
    }
    XYSeriesCollection my_data_series = new XYSeriesCollection();
    my_data_series.addSeries(data);
    for (XYSeries x : xy) {
        my_data_series.addSeries(x);
    }

    XYSeries thresh = new XYSeries("threshold");
    for (int j = 0; j < d.plots.length; j++) {
        thresh.add(j, threshold);
    }
    my_data_series.addSeries(thresh);

    //System.out.println(d.name);
    JFreeChart XYLineChart = ChartFactory.createXYLineChart(d.name, "Position", "Average", my_data_series,
            PlotOrientation.VERTICAL, true, true, false);
    bImage1 = (BufferedImage) XYLineChart.createBufferedImage(690, 337);
    imageIcon = new ImageIcon(bImage1);
    jLabel1.setIcon(imageIcon);
    jLabel1.revalidate();
    jLabel1.repaint();
    jButton1.setText("Save as PNG");
    jButton1.repaint();
    jButton1.revalidate();
    jButton1.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            chooser.setCurrentDirectory(new File("Documents"));
            int retrival = chooser.showSaveDialog(null);
            if (retrival == JFileChooser.APPROVE_OPTION) {
                try {
                    ImageIO.write(bImage1, "png", new File(chooser.getSelectedFile() + ".png"));
                } catch (IOException ex) {
                    System.out.println("Unable to Print!");
                }
            }
        }
    });
}

From source file:org.endeavour.mgmt.controller.servlet.CreateProjectPlan.java

private void createReportPage(Document aDocument, TaskSeries aTaskSeries, Date aStartDate, Date aEndDate,
        String aDescription) throws Exception {

    TaskSeriesCollection theDataset = new TaskSeriesCollection();
    theDataset.add(aTaskSeries);/*from ww  w. jav  a 2 s  .  c om*/

    DateAxis theDateRange = new DateAxis(TIMELINE);
    theDateRange.setMinimumDate(aStartDate);
    theDateRange.setMaximumDate(aEndDate);

    JFreeChart theChart = ChartFactory.createGanttChart(aDescription, ARTIFACTS, null, theDataset, true, false,
            false);
    CategoryPlot theCategoryPlot = theChart.getCategoryPlot();
    theCategoryPlot.setRangeAxis(theDateRange);

    BufferedImage theChartImage = theChart.createBufferedImage(780, 520);
    ByteArrayOutputStream theOutputStream = new ByteArrayOutputStream();
    ImageIO.write(theChartImage, "png", theOutputStream);
    Image theDocumentImage = Image.getInstance(theOutputStream.toByteArray());
    aDocument.add(theDocumentImage);
}

From source file:org.objectweb.proactive.benchmarks.timit.util.charts.BasicComparativeChartBuilder.java

/**
 * Generates in the specified folder a chart based on given data
 *
 * @param outputFolder The output folder
 *//*www. ja v a  2  s .  c  o  m*/
public void buildComparativeChart(File outputFolder) {
    // Check the series of files 
    if ((this.series == null) || (this.series.length < 2)) {
        throw new RuntimeException(
                "Cannot generate a comparative chart. You must provide at least 2 different files with the same structure.");
    }

    // Build new dataset
    this.dataset = new DefaultCategoryDataset();

    // This list will be used to store in 
    this.classNamesList = new java.util.ArrayList<String>();

    // Collect all possible classNames from the first serie
    this.collectAllClassNamesFrom(this.series[0]);

    // For each found className make a comparison between series
    Iterator<String> classNamesIterator = this.classNamesList.iterator();
    String className;
    int i;
    while (classNamesIterator.hasNext()) {
        className = classNamesIterator.next();
        // Iterate through  all series to get their values
        for (i = 0; i < this.series.length; i++) {
            // First generate chart for classname1
            // Fill the series (ie filename1) values
            fillDataset(this.series[i], className);
        }

        if (classNamesIterator.hasNext()) {
            // Put some white space
            fillWhiteSpace();
        }
    }

    String forChartName = "";

    // Iterate through  all series to get their values
    for (i = 0; i < this.series.length; i++) {
        forChartName += (this.series[i].getName() + (((i + 1) >= this.series.length) ? "" : "-"));
    }

    final JFreeChart chart = createChart();
    try {
        javax.imageio.ImageIO.write(chart.createBufferedImage(800, 600), "png",
                new java.io.File(outputFolder.getAbsoluteFile() + "/compareChart_" + forChartName + ".png"));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:ambit.ui.data.AmbitResultViewer.java

public void propertyChange(PropertyChangeEvent e) {

    result = e.getNewValue();// ww  w.  j  a  v  a  2 s.c  om

    System.out.println(e.getPropertyName());
    if (result == null) {
        image = null;
        return;
    }

    if (result instanceof FingerprintProfile) {
        String[] seriesNames = new String[] { ((FingerprintProfile) result).toString() };

        FingerprintProfile fp = (FingerprintProfile) result;
        String[] categoryNames = new String[fp.getLength()];
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        for (int i = 0; i < fp.getLength(); i++) {
            dataset.addValue(fp.getBitFrequency(i), seriesNames[0], new Integer(i));
        }
        JFreeChart chart = ChartFactory.createBarChart3D("Consensus fingerprint", "Bits", "Frequency", dataset,
                PlotOrientation.VERTICAL, true, false, false);
        chart.setBackgroundPaint(Color.white);
        chart.setAntiAlias(true);

        image = chart.createBufferedImage(450, 200);
        chart = null;
    }
    if (result instanceof SimilarityMatrix) {
        image = ((SimilarityMatrix) result).toImage();
    }
    if (image == null)
        label.setIcon(null);
    else
        label.setIcon(new ImageIcon(image));

}

From source file:edu.ku.brc.specify.plugins.ipadexporter.ChartHelper.java

/**
 * @param outFile//from w  ww  . j av a 2  s .co m
 * @param jfreeChart
 * @param width
 * @param height
 */
public void createImage(final File outFile, final JFreeChart jfreeChart, final int width, final int height) {
    if (jfreeChart != null) {
        BufferedImage bufImage = jfreeChart.createBufferedImage(width, height);
        try {
            ImageIO.write(bufImage, "PNG", outFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:inflor.knime.nodes.transform.create.TransformNodeModel.java

private byte[] createTransformPlot(FCSFrame summaryFrame, Entry<String, AbstractTransform> entry) {
    CategoryResponseChart chart = new CategoryResponseChart(entry.getKey(), entry.getValue());
    JFreeChart jfc = chart.createChart(summaryFrame);
    jfc.setBackgroundPaint(Color.WHITE);
    BufferedImage objBufferedImage = jfc.createBufferedImage(400, 300);
    ByteArrayOutputStream bas = new ByteArrayOutputStream();
    try {/*w  w w . jav a2 s  .  c om*/
        ImageIO.write(objBufferedImage, "png", bas);
    } catch (IOException e) {
        logger.error("Unable to create transform plot.", e);
    }
    return bas.toByteArray();
}