org.jfree.chart.ChartUtilities Java Examples

The following examples show how to use org.jfree.chart.ChartUtilities. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ChartComposite.java    From openstock with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(this.canvas.getShell(),
            SWT.SAVE);
    String[] extensions = {"*.png"};
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        //TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
                this.canvas.getSize().x, this.canvas.getSize().y);
    }
}
 
Example #2
Source File: StatisticsController.java    From JDeSurvey with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Controller that handles the chart generation for a question statistics
 * @param surveyDefinitionId
 * @param pageOrder
 * @param questionOrder
 * @param recordCount
 * @param response
 */
@Secured({"ROLE_ADMIN","ROLE_SURVEY_ADMIN"})
@RequestMapping(value="/chart/{surveyDefinitionId}/{questionId}")
public void generatePieChart(@PathVariable("surveyDefinitionId")  Long surveyDefinitionId,
							 @PathVariable("questionId")  Long questionId, 
							 HttpServletResponse response) {
	try {
		response.setContentType("image/png");
		long recordCount  = surveyService.surveyStatistic_get(surveyDefinitionId).getSubmittedCount();
		PieDataset pieDataSet= createDataset(questionId,recordCount);
		JFreeChart chart = createChart(pieDataSet, "");
		ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 340 ,200);
		response.getOutputStream().close();
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example #3
Source File: ChartComposite.java    From ECG-Viewer with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(this.canvas.getShell(),
            SWT.SAVE);
    String[] extensions = {"*.png"};
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        //TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
                this.canvas.getSize().x, this.canvas.getSize().y);
    }
}
 
Example #4
Source File: ChartWriterFactory.java    From entity-system-benchmarks with Apache License 2.0 6 votes vote down vote up
private static void generateChart(String benchmark, DefaultCategoryDataset dataset, int benchmarkCount) {
	JFreeChart chart = ChartFactory.createBarChart(
			benchmark, "framework", "throughput", dataset,
			PlotOrientation.HORIZONTAL, true, false, false);

	CategoryPlot plot = chart.getCategoryPlot();
	BarRenderer renderer = (BarRenderer) plot.getRenderer();
	renderer.setItemMargin(0);
	notSoUglyPlease(chart);
	
	String pngFile = getOutputName(benchmark);
	
	try {
		int height = 100 + benchmarkCount * 20;
		ChartUtilities.saveChartAsPNG(new File(pngFile), chart, 700, height);
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #5
Source File: AbstractChartPanel.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart in PNG format.
 * 
 * @throws IOException
 *             if there is an I/O error.
 */

@Override
public void doSaveAs() throws IOException {

	JFileChooser fileChooser = new JFileChooser();
	fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
	ExtensionFileFilter filter = new ExtensionFileFilter(localizationResources.getString("PNG_Image_Files"), ".png");
	fileChooser.addChoosableFileFilter(filter);

	int option = fileChooser.showSaveDialog(this);
	if (option == JFileChooser.APPROVE_OPTION) {
		String filename = fileChooser.getSelectedFile().getPath();
		if (isEnforceFileExtensions()) {
			if (!filename.endsWith(".png")) {
				filename = filename + ".png";
			}
		}
		ChartUtilities.saveChartAsPNG(new File(filename), this.chart, getWidth(), getHeight());
	}

}
 
Example #6
Source File: ChartComposite.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(this.canvas.getShell(),
            SWT.SAVE);
    String[] extensions = {"*.png"};
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        //TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
                this.canvas.getSize().x, this.canvas.getSize().y);
    }
}
 
Example #7
Source File: ServletUtilities.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Saves the chart as a PNG format file in the temporary directory and
 * populates the {@link ChartRenderingInfo} object which can be used to
 * generate an HTML image map.
 *
 * @param chart  the chart to be saved (<code>null</code> not permitted).
 * @param width  the width of the chart.
 * @param height  the height of the chart.
 * @param info  the ChartRenderingInfo object to be populated
 *              (<code>null</code> permitted).
 * @param session  the HttpSession of the client (if <code>null</code>, the
 *                 temporary file is marked as "one-time" and deleted by
 *                 the {@link DisplayChart} servlet right after it is
 *                 streamed to the client).
 *
 * @return The filename of the chart saved in the temporary directory.
 *
 * @throws IOException if there is a problem saving the file.
 */
public static String saveChartAsPNG(JFreeChart chart, int width, int height,
        ChartRenderingInfo info, HttpSession session) throws IOException {

    if (chart == null) {
        throw new IllegalArgumentException("Null 'chart' argument.");
    }
    ServletUtilities.createTempDir();
    String prefix = ServletUtilities.tempFilePrefix;
    if (session == null) {
        prefix = ServletUtilities.tempOneTimeFilePrefix;
    }
    File tempFile = File.createTempFile(prefix, ".png",
            new File(System.getProperty("java.io.tmpdir")));
    ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
    if (session != null) {
        ServletUtilities.registerChartForDeletion(tempFile, session);
    }
    return tempFile.getName();

}
 
Example #8
Source File: ChartComposite.java    From SIMVA-SoS with Apache License 2.0 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(this.canvas.getShell(),
            SWT.SAVE);
    String[] extensions = {"*.png"};
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        //TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
                this.canvas.getSize().x, this.canvas.getSize().y);
    }
}
 
Example #9
Source File: ChartComposite.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(this.canvas.getShell(), 
            SWT.SAVE);
    String[] extensions = { "*.png" };
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        //TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart, 
                this.canvas.getSize().x, this.canvas.getSize().y);
    }
}
 
Example #10
Source File: PanamaHitek_ThermometerChart.java    From PanamaHitek_Arduino with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void buildPlot1() {
    setColorLimits();
    dataset = new DefaultValueDataset(30);
    ThermometerPlot thermometerplot = new ThermometerPlot(dataset);
    thermometerplot.setRange(plotBottonLimit, plotTopLimit);
    thermometerplot.setUnits(ThermometerPlot.UNITS_CELCIUS);
    thermometerplot.setSubrange(0, greenBottomLimit, greenTopLimit);
    thermometerplot.setSubrangePaint(0, Color.green);
    thermometerplot.setSubrange(1, yellowBottomLimit, yellowTopLimit);
    thermometerplot.setSubrangePaint(1, Color.yellow);
    thermometerplot.setSubrange(2, redBottomLimit, redTopLimit);
    thermometerplot.setSubrangePaint(2, Color.red);
    JFreeChart jfreechart = new JFreeChart(plotTitle, thermometerplot);
    ChartUtilities.applyCurrentTheme(jfreechart);
    add(new ChartPanel(jfreechart));
}
 
Example #11
Source File: ServletUtilities.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Saves the chart as a PNG format file in the temporary directory and
 * populates the {@link ChartRenderingInfo} object which can be used to 
 * generate an HTML image map.
 *
 * @param chart  the chart to be saved (<code>null</code> not permitted).
 * @param width  the width of the chart.
 * @param height  the height of the chart.
 * @param info  the ChartRenderingInfo object to be populated 
 *              (<code>null</code> permitted).
 * @param session  the HttpSession of the client (if <code>null</code>, the
 *                 temporary file is marked as "one-time" and deleted by 
 *                 the {@link DisplayChart} servlet right after it is
 *                 streamed to the client).
 *
 * @return The filename of the chart saved in the temporary directory.
 *
 * @throws IOException if there is a problem saving the file.
 */
public static String saveChartAsPNG(JFreeChart chart, int width, int height,
        ChartRenderingInfo info, HttpSession session) throws IOException {

    if (chart == null) {
        throw new IllegalArgumentException("Null 'chart' argument.");   
    }
    ServletUtilities.createTempDir();
    String prefix = ServletUtilities.tempFilePrefix;
    if (session == null) {
        prefix = ServletUtilities.tempOneTimeFilePrefix;
    }
    File tempFile = File.createTempFile(prefix, ".png", 
            new File(System.getProperty("java.io.tmpdir")));
    ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
    if (session != null) {
        ServletUtilities.registerChartForDeletion(tempFile, session);
    }
    return tempFile.getName();

}
 
Example #12
Source File: ChartWriter.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
public void drawChart(String filename, int width, int height) throws IOException {
  // Create plot
  NumberAxis xAxis = new NumberAxis(xAxisLabel);
  NumberAxis yAxis = new NumberAxis(yAxisLabel);
  XYSplineRenderer renderer = new XYSplineRenderer();
  XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
  plot.setBackgroundPaint(Color.lightGray);
  plot.setDomainGridlinePaint(Color.white);
  plot.setRangeGridlinePaint(Color.white);
  plot.setAxisOffset(new RectangleInsets(4, 4, 4, 4));

  // Create chart
  JFreeChart chart = new JFreeChart(chartTitle, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
  ChartUtilities.applyCurrentTheme(chart);
  ChartPanel chartPanel = new ChartPanel(chart, false);

  // Draw png
  BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
  Graphics graphics = bi.getGraphics();
  chartPanel.setBounds(0, 0, width, height);
  chartPanel.paint(graphics);
  ImageIO.write(bi, "png", new File(filename));
}
 
Example #13
Source File: ExportJFreeChart.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param out
 * @return extension png or jpg for usage as file name extension.
 */
public String write(final OutputStream out)
{
  final JFreeChart chart = getJFreeChart();
  final int width = getWidth();
  final int height = getHeight();
  String extension = null;
  try {
    if (getImageType() == JFreeChartImageType.PNG) {
      extension = "png";
      ChartUtilities.writeChartAsPNG(out, chart, width, height);
    } else {
      extension = "jpg";
      ChartUtilities.writeChartAsJPEG(out, chart, width, height);
    }
  } catch (final IOException ex) {
    log.error("Exception encountered " + ex, ex);
  }
  return extension;
}
 
Example #14
Source File: ChartComposite.java    From ccu-historian with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(this.canvas.getShell(),
            SWT.SAVE);
    String[] extensions = {"*.png"};
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        //TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
                this.canvas.getSize().x, this.canvas.getSize().y);
    }
}
 
Example #15
Source File: ChartComposite.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(this.canvas.getShell(),
            SWT.SAVE);
    String[] extensions = {"*.png"};
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        //TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
                this.canvas.getSize().x, this.canvas.getSize().y);
    }
}
 
Example #16
Source File: Timer.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void saveChart(String op) {
    XYSeries series = new XYSeries(op);
    int i = 0;
    for (Long duration : stats.get(op)) {
        series.add(++i, duration);
    }
    final XYSeriesCollection data = new XYSeriesCollection(series);
    final JFreeChart chart = ChartFactory.createXYLineChart(
            op,
            "Operations",
            "Duration (ms)",
            data,
            PlotOrientation.VERTICAL,
            true,
            true,
            false
    );
    try {
        ChartUtilities.saveChartAsPNG(
                new File(CHARTS_DIR, op.replace(" ", "_") + ".png"),
                chart, 640, 480);
    } catch (IOException ex) {
        log.warn("Unable to save chart for operation '" + op + "'.");
    }
}
 
Example #17
Source File: MultipleAxisChart.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void finish(java.awt.Dimension preferredSize) {
  ChartUtilities.applyCurrentTheme(chart);

  XYPlot plot = (XYPlot) chart.getPlot();
  for (int i = 0; i < axisNum; i++) {
    XYItemRenderer renderer = plot.getRenderer(i);
    if (renderer == null)
      continue;

    renderer.setSeriesPaint(0, colors[i]);

    ValueAxis axis = plot.getRangeAxis(i);
    axis.setLabelPaint(colors[i]);
    axis.setTickLabelPaint(colors[i]);
  }

  ChartPanel chartPanel = new ChartPanel(chart);
  chartPanel.setPreferredSize(preferredSize);
  chartPanel.setDomainZoomable(true);
  chartPanel.setRangeZoomable(true);
}
 
Example #18
Source File: ImagePanel.java    From moa with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Method for save the images.
 *
 * @throws IOException
 */
@Override
public void doSaveAs() throws IOException {

    JFileChooser fileChooser = new JFileChooser();
    ExtensionFileFilter filterPNG = new ExtensionFileFilter("PNG Image Files", ".png");
    fileChooser.addChoosableFileFilter(filterPNG);

    ExtensionFileFilter filterJPG = new ExtensionFileFilter("JPG Image Files", ".jpg");
    fileChooser.addChoosableFileFilter(filterJPG);

    ExtensionFileFilter filterEPS = new ExtensionFileFilter("EPS Image Files", ".eps");
    fileChooser.addChoosableFileFilter(filterEPS);

    ExtensionFileFilter filterSVG = new ExtensionFileFilter("SVG Image Files", ".svg");
    fileChooser.addChoosableFileFilter(filterSVG);
    fileChooser.setCurrentDirectory(null);
    int option = fileChooser.showSaveDialog(this);
    if (option == JFileChooser.APPROVE_OPTION) {
        String fileDesc = fileChooser.getFileFilter().getDescription();
        if (fileDesc.startsWith("PNG")) {
            if (!fileChooser.getSelectedFile().getName().toUpperCase().endsWith("PNG")) {
                ChartUtilities.saveChartAsPNG(new File(fileChooser.getSelectedFile().getAbsolutePath() + ".png"), this.chart, this.getWidth(), this.getHeight());
            } else {
                ChartUtilities.saveChartAsPNG(fileChooser.getSelectedFile(), this.chart, this.getWidth(), this.getHeight());
            }
        } else if (fileDesc.startsWith("JPG")) {
            if (!fileChooser.getSelectedFile().getName().toUpperCase().endsWith("JPG")) {
                ChartUtilities.saveChartAsJPEG(new File(fileChooser.getSelectedFile().getAbsolutePath() + ".jpg"), this.chart, this.getWidth(), this.getHeight());
            } else {
                ChartUtilities.saveChartAsJPEG(fileChooser.getSelectedFile(), this.chart, this.getWidth(), this.getHeight());
            }
        }

    }//else
}
 
Example #19
Source File: ChartVirtualSensor.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Plots the chart and sends it in the form of ByteArrayOutputStream to
 * outside.
 * 
 * @return Returns the byteArrayOutputStream.
 */
public synchronized ByteArrayOutputStream writePlot ( ) {
   if ( !changed ) return byteArrayOutputStream;
   byteArrayOutputStream.reset( );
   try {
      ChartUtilities.writeChartAsPNG( byteArrayOutputStream , chart , width , height , false , 8 );
      
   } catch ( IOException e ) {
      logger.warn( e.getMessage( ) , e );
   }
   return byteArrayOutputStream;
}
 
Example #20
Source File: BaseChartPanel.java    From nmonvisualizer with Apache License 2.0 5 votes vote down vote up
public final void saveChart(String directory, String filename) {
    filename = validateSaveFileName(filename);

    File chartFile = new File(directory, filename);

    try {
        ChartUtilities.saveChartAsPNG(chartFile, getChart(), saveWidth, saveHeight);
    }
    catch (IOException ioe) {
        logger.error("could not save chart '" + filename + "' to directory '" + directory + "'", ioe);
    }
}
 
Example #21
Source File: ReportGenerator.java    From nmonvisualizer with Apache License 2.0 5 votes vote down vote up
private boolean saveChart(BaseChartDefinition definition, Iterable<? extends DataSet> dataSets,
        File saveDirectory) {
    JFreeChart chart = factory.createChart(definition, dataSets);

    if (chartHasData(chart)) {
        File chartFile = new File(saveDirectory, definition.getShortName().replace(" ", "_") + ".png");

        try {
            ChartUtilities.saveChartAsPNG(chartFile, chart, definition.getWidth(), definition.getHeight());
        }
        catch (IOException ioe) {
            System.err.println("cannot create chart " + chartFile.getName());
        }

        if (writeChartData) {
            writeChartData(chart, definition, saveDirectory);
        }

        System.out.print('.');
        System.out.flush();

        return true;
    }
    else {
        return false;
    }
}
 
Example #22
Source File: APAvsDistance.java    From Juicebox with MIT License 5 votes vote down vote up
private static void plotChart(String SaveFolderPath, XYSeries results) {
    File file = new File(SaveFolderPath + "/results.png");

    final XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(results);

    JFreeChart Chart = ChartFactory.createXYLineChart(
            "APA vs Distance",
            "Distance Bucket",
            "APA Score",
            dataset,
            PlotOrientation.VERTICAL,
            true, true, false);

   /*
   LogarithmicAxis logAxis= new LogarithmicAxis("Distance (log)");
   XYPlot plot= Chart.getXYPlot();
   plot.setDomainAxis(logAxis);
   XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer)plot.getRenderer();
   renderer.setSeriesShapesVisible(0, true);
   ChartFrame frame = new ChartFrame("My Chart", Chart);
   frame.pack();
   frame.setVisible(true);
   */

    int width = 640;   /* Width of the image */
    int height = 480;  /* Height of the image */

    try {
        ChartUtilities.saveChartAsPNG(file, Chart, width, height);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
 
Example #23
Source File: EESGenerator.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
public void createChartToOutputStream(DesignOptions options,
		ChartRenderingInfo renderingInfo, OutputStream outputStream) {
	try {
           Map<String, OXFFeatureCollection> entireCollMap = getFeatureCollectionFor(options, true);
           JFreeChart chart = producePresentation(entireCollMap, options);
           chart.removeLegend();
           int width = options.getWidth();
           int height = options.getHeight();
           ChartUtilities.writeChartAsPNG(outputStream, chart, width, height, renderingInfo);
       } catch (Exception e) {
           LOGGER.warn("Error while rendering chart.", e);
       }
}
 
Example #24
Source File: cfCHART.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private String saveChartToFile(JFreeChart chart, byte _format, int width, int height, ChartRenderingInfo info) throws IOException {
	File tempFile;
	if (_format == FORMAT_JPG) {
		tempFile = File.createTempFile("cfchart", ".jpeg", cfchartDirectory);
		ChartUtilities.saveChartAsJPEG(tempFile, chart, width, height, info);
	} else {
		tempFile = File.createTempFile("cfchart", ".png", cfchartDirectory);
		ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
	}
	String filename = tempFile.getName();

	// Check if charts are being cached
	if (storageCacheSize > 0) {
		synchronized (storageCache) {
			// If we've reached the cache limit then delete the oldest cached chart.
			if (storageCache.size() == storageCacheSize) {
				String oldestChart = storageCache.remove(0);
				File fileToDelete = new File(cfchartDirectory, oldestChart);
				fileToDelete.delete();
			}

			// Add the new chart to the end of the list of cached charts
			storageCache.add(filename);
		}
	}

	return filename;
}
 
Example #25
Source File: AbstractChartBuilder.java    From livingdoc-confluence with GNU General Public License v3.0 5 votes vote down vote up
public String getChartMap(String chartMapId) throws IOException {
    StringWriter writer = new StringWriter();
    PrintWriter pw = new PrintWriter(writer);

    try {
        ChartUtilities.writeImageMap(pw, chartMapId, chartRenderingInfo, new StandardToolTipTagFragmentGenerator(),
            new StandardURLTagFragmentGenerator());
    } finally {
        IOUtils.closeQuietly(pw);
    }

    return writer.toString();
}
 
Example #26
Source File: cfCHART.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private byte[] generateChart(JFreeChart chart, byte _format, int width, int height, ChartRenderingInfo info) throws IOException {
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	if (_format == FORMAT_JPG)
		ChartUtilities.writeChartAsJPEG(out, chart, width, height, info);
	else
		ChartUtilities.writeChartAsPNG(out, chart, width, height, info);
	out.close();

	return out.toByteArray();
}
 
Example #27
Source File: VisualizePanelCharts2D.java    From KEEL with GNU General Public License v3.0 5 votes vote down vote up
private void topngjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topngjButtonActionPerformed
    // Save chart as a PNG image
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Save chart");
    KeelFileFilter fileFilter = new KeelFileFilter();
    fileFilter.addExtension("png");
    fileFilter.setFilterName("PNG images (.png)");
    chooser.setFileFilter(fileFilter);
    chooser.setCurrentDirectory(Path.getFilePath());
    int opcion = chooser.showSaveDialog(this);
    Path.setFilePath(chooser.getCurrentDirectory());

    if (opcion == JFileChooser.APPROVE_OPTION) {
        String nombre = chooser.getSelectedFile().getAbsolutePath();
        if (!nombre.toLowerCase().endsWith(".png")) {
            // Add correct extension
            nombre += ".png";
        }
        File tmp = new File(nombre);
        if (!tmp.exists() || JOptionPane.showConfirmDialog(this, "File " + nombre + " already exists. Do you want to replace it?",
                "Confirm", JOptionPane.YES_NO_OPTION, 3) == JOptionPane.YES_OPTION) {
            try {
                chart2.setBackgroundPaint(Color.white);
                ChartUtilities.saveChartAsPNG(new File(nombre), chart2,
                        1024, 768);
            } catch (Exception exc) {
            }
        }
    }
}
 
Example #28
Source File: ChartComponent.java    From software-demo with MIT License 5 votes vote down vote up
/**
 * 输出成图片
 */
public static boolean saveChartPNG(File target, String materialsId, String year, int month1, int month2) { 
	try {
		FileOutputStream fos = new FileOutputStream(target);
		JFreeChart chart = createChart(materialsId, year, month1, month2);
		//保存为图片 大小 1100 * 800
		ChartUtilities.saveChartAsPNG(target, chart, 1100, 800);
		fos.flush();
		fos.close();
		return true;
	} catch (Exception e) {
		return false;
	}
}
 
Example #29
Source File: DerivedCounter.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
protected void writeChartToFile(String path, JFreeChart chart)
{
    try
    {
        ChartUtilities.saveChartAsPNG(new File(path), chart, 800, 400);
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
 
Example #30
Source File: UserChartController.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String type = request.getParameter("type");
    CategoryDataset dataset = createDataset(type);
    JFreeChart chart = createChart(dataset, request);

    int imageHeight = Math.max(IMAGE_MIN_HEIGHT, 15 * dataset.getColumnCount());

    ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, imageHeight);
    return null;
}