org.jfree.chart.ChartUtils Java Examples

The following examples show how to use org.jfree.chart.ChartUtils. 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: EChartPanel.java    From old-mzmine3 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.
 */
@Override
public void doSaveAs() throws IOException {
  JFileChooser fileChooser = new JFileChooser();
  fileChooser.setCurrentDirectory(this.getDefaultDirectoryForSaveAs());
  FileNameExtensionFilter filter =
      new FileNameExtensionFilter(localizationResources.getString("PNG_Image_Files"), "png");
  fileChooser.addChoosableFileFilter(filter);
  fileChooser.setFileFilter(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";
      }
    }
    ChartUtils.saveChartAsPNG(new File(filename), getChart(), getWidth(), getHeight(),
        getChartRenderingInfo());
  }
}
 
Example #2
Source File: EChartPanel.java    From mzmine3 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.
 */
@Override
public void doSaveAs() throws IOException {
  JFileChooser fileChooser = new JFileChooser();
  fileChooser.setCurrentDirectory(this.getDefaultDirectoryForSaveAs());
  FileNameExtensionFilter filter =
      new FileNameExtensionFilter(localizationResources.getString("PNG_Image_Files"), "png");
  fileChooser.addChoosableFileFilter(filter);
  fileChooser.setFileFilter(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";
      }
    }
    ChartUtils.saveChartAsPNG(new File(filename), getChart(), getWidth(), getHeight(),
        getChartRenderingInfo());
  }
}
 
Example #3
Source File: UnitStatusPage.java    From freeacs with MIT License 6 votes vote down vote up
/**
 * Gets the report chart image bytes.
 *
 * @param chartMaker the chart maker
 * @param chart the chart
 * @param width the width
 * @param height the height
 * @return the report chart image bytes
 * @throws Exception the exception
 */
public static byte[] getReportChartImageBytes(
    Chart<?> chartMaker, JFreeChart chart, int width, int height) throws Exception {
  if (chart == null && chartMaker != null) {
    chart = chartMaker.makeTimeChart(null, null, null, null);
  } else if (chart == null) {
    throw new IllegalArgumentException("Chart<?> and JFreeChart is NULL.");
  }
  if (chart.getPlot() instanceof XYPlot) {
    XYPlot plot = (XYPlot) chart.getPlot();
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setDefaultShapesVisible(true);
    renderer.setDrawOutlines(true);
    renderer.setUseFillPaint(true);
    renderer.setDefaultFillPaint(Color.white);
  }
  ByteArrayOutputStream image = new ByteArrayOutputStream();
  ChartUtils.writeChartAsPNG(image, chart, width, height);
  return image.toByteArray();
}
 
Example #4
Source File: EChartPanel.java    From mzmine2 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.
 */
@Override
public void doSaveAs() throws IOException {
  JFileChooser fileChooser = new JFileChooser();
  fileChooser.setCurrentDirectory(this.getDefaultDirectoryForSaveAs());
  FileNameExtensionFilter filter =
      new FileNameExtensionFilter(localizationResources.getString("PNG_Image_Files"), "png");
  fileChooser.addChoosableFileFilter(filter);
  fileChooser.setFileFilter(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";
      }
    }
    ChartUtils.saveChartAsPNG(new File(filename), getChart(), getWidth(), getHeight(),
        getChartRenderingInfo());
  }
}
 
Example #5
Source File: ChartRenderer.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Draw a JFreeChart to a base64 encoded image based on values from a MultiTable.
 * @param table MultiTable to retrieve values from
 * @param config chart configuration options
 */
public static String drawChartAsBase64(MultiTable table, MultiTableChartConfig config)
    throws IOException {
  
  JFreeChart chart = createChart(table, config);

  byte[] imgBytes = ChartUtils.encodeAsPNG(chart.createBufferedImage(config.getWidth(),
      config.getHeight()));
  return new String(Base64.getEncoder().encode(imgBytes));
}
 
Example #6
Source File: ChartExportUtil.java    From old-mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
public static void writeChartToPNG(JFreeChart chart, ChartRenderingInfo info, int width,
    int height, File fileName, int resolution) throws IOException {
  if (resolution == 72)
    writeChartToPNG(chart, info, width, height, fileName);
  else {
    OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
    try {
      BufferedImage image = paintScaledChartToBufferedImage(chart, info, out, width, height,
          resolution, BufferedImage.TYPE_INT_ARGB);
      out.write(ChartUtils.encodeAsPNG(image));
    } finally {
      out.close();
    }
  }
}
 
Example #7
Source File: ChartExportUtil.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
public static void writeChartToPNG(JFreeChart chart, ChartRenderingInfo info, int width,
    int height, File fileName, int resolution) throws IOException {
  if (resolution == 72)
    writeChartToPNG(chart, info, width, height, fileName);
  else {
    OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
    try {
      BufferedImage image = paintScaledChartToBufferedImage(chart, info, out, width, height,
          resolution, BufferedImage.TYPE_INT_ARGB);
      out.write(ChartUtils.encodeAsPNG(image));
    } finally {
      out.close();
    }
  }
}
 
Example #8
Source File: EventChartController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequestMapping( value = { "/{uid}/data", "/{uid}/data.png" }, method = RequestMethod.GET )
public void getChart(
    @PathVariable( "uid" ) String uid,
    @RequestParam( value = "date", required = false ) Date date,
    @RequestParam( value = "ou", required = false ) String ou,
    @RequestParam( value = "width", defaultValue = "800", required = false ) int width,
    @RequestParam( value = "height", defaultValue = "500", required = false ) int height,
    @RequestParam( value = "attachment", required = false ) boolean attachment,
    HttpServletResponse response ) throws IOException, WebMessageException
{
    EventChart chart = eventChartService.getEventChart( uid ); // TODO no acl?

    if ( chart == null )
    {
        throw new WebMessageException( WebMessageUtils.notFound( "Event chart does not exist: " + uid ) );
    }

    OrganisationUnit unit = ou != null ? organisationUnitService.getOrganisationUnit( ou ) : null;

    JFreeChart jFreeChart = chartService.getJFreeChart( chart, date, unit, i18nManager.getI18nFormat() );

    String filename = CodecUtils.filenameEncode( chart.getName() ) + ".png";

    contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PNG, CacheStrategy.RESPECT_SYSTEM_SETTING, filename, attachment );

    ChartUtils.writeChartAsPNG( response.getOutputStream(), jFreeChart, width, height );
}
 
Example #9
Source File: ChartController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequestMapping( value = { "/data", "/data.png" }, method = RequestMethod.GET )
public void getChart(
    @RequestParam( value = "in" ) String indicatorUid,
    @RequestParam( value = "ou" ) String organisationUnitUid,
    @RequestParam( value = "periods", required = false ) boolean periods,
    @RequestParam( value = "width", defaultValue = "800", required = false ) int width,
    @RequestParam( value = "height", defaultValue = "500", required = false ) int height,
    @RequestParam( value = "skipTitle", required = false ) boolean skipTitle,
    @RequestParam( value = "attachment", required = false ) boolean attachment,
    HttpServletResponse response ) throws IOException
{
    Indicator indicator = indicatorService.getIndicator( indicatorUid );
    OrganisationUnit unit = organisationUnitService.getOrganisationUnit( organisationUnitUid );

    JFreeChart chart;

    if ( periods )
    {
        chart = chartService.getJFreePeriodChart( indicator, unit, !skipTitle, i18nManager.getI18nFormat() );
    }
    else
    {
        chart = chartService.getJFreeOrganisationUnitChart( indicator, unit, !skipTitle, i18nManager.getI18nFormat() );
    }

    contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PNG, CacheStrategy.RESPECT_SYSTEM_SETTING, "chart.png", attachment );

    ChartUtils.writeChartAsPNG( response.getOutputStream(), chart, width, height );
}
 
Example #10
Source File: ChartController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequestMapping( value = { "/{uid}/data", "/{uid}/data.png" }, method = RequestMethod.GET )
public void getChart(
    @PathVariable( "uid" ) String uid,
    @RequestParam( value = "date", required = false ) Date date,
    @RequestParam( value = "ou", required = false ) String ou,
    @RequestParam( value = "width", defaultValue = "800", required = false ) int width,
    @RequestParam( value = "height", defaultValue = "500", required = false ) int height,
    @RequestParam( value = "attachment", required = false ) boolean attachment,
    HttpServletResponse response ) throws IOException, WebMessageException
{
    final Visualization visualization = visualizationService.getVisualizationNoAcl( uid );
    final Chart chart = convertToChart( visualization );

    if ( chart == null )
    {
        throw new WebMessageException( WebMessageUtils.notFound( "Chart does not exist: " + uid ) );
    }

    OrganisationUnit unit = ou != null ? organisationUnitService.getOrganisationUnit( ou ) : null;

    JFreeChart jFreeChart = chartService.getJFreeChart( chart, date, unit, i18nManager.getI18nFormat() );

    String filename = CodecUtils.filenameEncode( chart.getName() ) + ".png";

    contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PNG, CacheStrategy.RESPECT_SYSTEM_SETTING, filename, attachment );

    ChartUtils.writeChartAsPNG( response.getOutputStream(), jFreeChart, width, height );
}
 
Example #11
Source File: ChartResult.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Executes the result. Writes the given chart as a PNG to the servlet
 * output stream.
 *
 * @param invocation an encapsulation of the action execution state.
 * @throws Exception if an error occurs when creating or writing the chart
 *                   to the servlet output stream.
 */
@Override
public void execute( ActionInvocation invocation )
    throws Exception
{
    JFreeChart stackChart = (JFreeChart) invocation.getStack().findValue( "chart" );

    chart = stackChart != null ? stackChart : chart;

    Integer stackHeight = (Integer) invocation.getStack().findValue( "height" );

    height = stackHeight != null && stackHeight > 0 ? stackHeight : height != null ? height : DEFAULT_HEIGHT;

    Integer stackWidth = (Integer) invocation.getStack().findValue( "width" );

    width = stackWidth != null && stackWidth > 0 ? stackWidth : width != null ? width : DEFAULT_WIDTH;

    String stackFilename = (String) invocation.getStack().findValue( "filename" );

    filename = StringUtils.defaultIfEmpty( stackFilename, DEFAULT_FILENAME );

    if ( chart == null )
    {
        log.warn( "No chart found" );
        return;
    }

    HttpServletResponse response = ServletActionContext.getResponse();
    ContextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PNG, true, filename, false );

    OutputStream os = response.getOutputStream();
    ChartUtils.writeChartAsPNG( os, chart, width, height );
    os.flush();
}
 
Example #12
Source File: ChartRenderer.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Draw a JFreeChart to a base64 encoded image based on values from a MultiTable.
 * @param person Person to retrieve attribute values from
 * @param config chart configuration options
 */
public static String drawChartAsBase64(Person person, PersonChartConfig config)
    throws IOException {
  
  JFreeChart chart = createChart(person, config);

  byte[] imgBytes = ChartUtils.encodeAsPNG(chart.createBufferedImage(config.getWidth(),
      config.getHeight()));
  return new String(Base64.getEncoder().encode(imgBytes));
}
 
Example #13
Source File: ChartRenderer.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Draw a JFreeChart to an image based on values from a MultiTable.
 * @param person Person to retrieve attributes from
 * @param config chart configuration options
 */
public static void drawChartAsFile(Person person, PersonChartConfig config) {
  
  JFreeChart chart = createChart(person, config);
  
  // Save the chart as a PNG image to the file system
  try {
    ChartUtils.saveChartAsPNG(new File(config.getFilename()), chart, config.getWidth(),
        config.getHeight());
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example #14
Source File: ChartRenderer.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Draw a JFreeChart to an image based on values from a MultiTable.
 * @param table MultiTable to retrieve values from
 * @param config chart configuration options
 */
public static void drawChartAsFile(MultiTable table, MultiTableChartConfig config) {
  
  JFreeChart chart = createChart(table, config);
  
  // Save the chart as a PNG image to the file system
  try {
    ChartUtils.saveChartAsPNG(new File(config.getFilename()), chart, config.getWidth(),
        config.getHeight());
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example #15
Source File: UserChartController.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping
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());

    ChartUtils.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, imageHeight);
    return null;
}
 
Example #16
Source File: ChartImageResource.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
protected byte[] getImageData(Attributes aAttributes)
{
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ChartUtils.writeChartAsPNG(bos, chart, width, height);
        return bos.toByteArray();
    }
    catch (IOException e) {
        return new byte[0];
    }
}
 
Example #17
Source File: ChartExportUtil.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
public static void writeChartToPNG(JFreeChart chart, ChartRenderingInfo info, int width,
    int height, File fileName, int resolution) throws IOException {
  if (resolution == 72)
    writeChartToPNG(chart, info, width, height, fileName);
  else {
    OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
    try {
      BufferedImage image = paintScaledChartToBufferedImage(chart, info, out, width, height,
          resolution, BufferedImage.TYPE_INT_ARGB);
      out.write(ChartUtils.encodeAsPNG(image));
    } finally {
      out.close();
    }
  }
}
 
Example #18
Source File: UserChartController.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping
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());

    ChartUtils.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, imageHeight);
    return null;
}
 
Example #19
Source File: ScatterPlot.java    From Benchmark with GNU General Public License v2.0 4 votes vote down vote up
public void writeChartToFile(File f, int height) throws IOException {
    FileOutputStream stream = new FileOutputStream(f);
    ChartUtils.writeChartAsPNG(stream, chart, (int)Math.round(height*1.4), height);
    stream.close();
}
 
Example #20
Source File: ChartExportUtil.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
public static void writeChartToJPEG(JFreeChart chart, int width, int height, File fileName)
    throws IOException {
  ChartUtils.saveChartAsJPEG(fileName, chart, width, height);
}
 
Example #21
Source File: ChartExportUtil.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
public static void writeChartToPNG(JFreeChart chart, ChartRenderingInfo info, int width,
    int height, File fileName) throws IOException {
  ChartUtils.saveChartAsPNG(fileName, chart, width, height, info);
}
 
Example #22
Source File: ChartExportUtil.java    From old-mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
public static void writeChartToJPEG(JFreeChart chart, int width, int height, File fileName)
    throws IOException {
  ChartUtils.saveChartAsJPEG(fileName, chart, width, height);
}
 
Example #23
Source File: ChartExportUtil.java    From old-mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
public static void writeChartToPNG(JFreeChart chart, ChartRenderingInfo info, int width,
    int height, File fileName) throws IOException {
  ChartUtils.saveChartAsPNG(fileName, chart, width, height, info);
}
 
Example #24
Source File: ChartController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@RequestMapping( value = { "/history/data", "/history/data.png" }, method = RequestMethod.GET )
public void getHistoryChart(
    @RequestParam String de,
    @RequestParam String co,
    @RequestParam String cp,
    @RequestParam String pe,
    @RequestParam String ou,
    @RequestParam( defaultValue = "525", required = false ) int width,
    @RequestParam( defaultValue = "300", required = false ) int height,
    HttpServletResponse response ) throws IOException, WebMessageException
{
    DataElement dataElement = dataElementService.getDataElement( de );

    if ( dataElement == null )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Data element does not exist: " + de ) );
    }

    CategoryOptionCombo categoryOptionCombo = categoryService.getCategoryOptionCombo( co );

    if ( categoryOptionCombo == null )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Category option combo does not exist: " + co ) );
    }

    CategoryOptionCombo attributeOptionCombo = categoryService.getCategoryOptionCombo( cp );

    if ( attributeOptionCombo == null )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Category option combo does not exist: " + cp ) );
    }

    Period period = PeriodType.getPeriodFromIsoString( pe );

    if ( period == null )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Period does not exist: " + pe ) );
    }

    OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit( ou );

    if ( organisationUnit == null )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Organisation unit does not exist: " + ou ) );
    }

    contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PNG, CacheStrategy.RESPECT_SYSTEM_SETTING, "chart.png", false );

    JFreeChart chart = chartService.getJFreeChartHistory( dataElement, categoryOptionCombo, attributeOptionCombo, period, organisationUnit, 13, i18nManager.getI18nFormat() );

    ChartUtils.writeChartAsPNG( response.getOutputStream(), chart, width, height );
}
 
Example #25
Source File: ReportPage.java    From freeacs with MIT License 4 votes vote down vote up
private void displayReportChartWithImageMap(
    Map<String, Object> root,
    int numberOfColumns,
    int averageLengthPrLegend,
    List<String> aggregation,
    HttpSession session) {
  StringWriter stringWriter = new StringWriter();
  PrintWriter writer = new PrintWriter(stringWriter);

  boolean shouldZoom = true;

  switch (reportType) {
    case JOB:
    case UNIT:
      shouldZoom = false;
      break;
    default:
      break;
  }

  String clickablePointUrl = "";
  if (shouldZoom || periodType.getSelected().isLongerThan(PeriodType.HOUR)) {
    clickablePointUrl =
        generateClickablePointUrl(
            periodType.getSelected(),
            reportType.getName(),
            method.getSelected(),
            optionalmethod.getSelected());
  }

  XYPlot plot = (XYPlot) chart.getPlot();
  XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
  XYURLGenerator urls = new ReportURLGenerator(clickablePointUrl, chart, aggregation);
  renderer.setURLGenerator(urls);
  XYSeriesLabelGenerator slg =
      new CustomXYSeriesLabelGenerator("javascript:xAPS.report.updateReport(%d);");
  renderer.setLegendItemURLGenerator(slg);
  renderer.setDefaultShapesVisible(true);
  renderer.setDrawOutlines(true);
  renderer.setUseFillPaint(true);
  renderer.setDefaultFillPaint(Color.white);

  try {
    ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
    ByteArrayOutputStream image = new ByteArrayOutputStream();

    int chartWidth = 700 + 10 * averageLengthPrLegend * numberOfColumns + 35 * numberOfColumns;

    ChartUtils.writeChartAsPNG(image, chart, chartWidth, 400, info);

    session.setAttribute("JFreeChartPNG" + reportType.getName(), image.toByteArray());

    ImageMapUtils.writeImageMap(
        writer,
        "chart" + reportType.getName(),
        info,
        arg0 -> " title=\"" + arg0 + "\" alt=\"" + arg0 + "\"",
        arg0 -> " href=\"" + arg0 + "\"");

    writer.println(
        "<img src=\""
            + Page.REPORT.getUrl()
            + "&type="
            + reportType.getName()
            + "&image=true&d="
            + new Date().getTime()
            + "\" border=\"0\" usemap=\"#chart"
            + reportType.getName()
            + "\" id=\"ImageMapImg\" alt=\"ReportImage\"/>");
    writer.close();

    root.put("imagemap", stringWriter.toString());
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example #26
Source File: ChartExportUtil.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
public static void writeChartToJPEG(JFreeChart chart, int width, int height, File fileName)
    throws IOException {
  ChartUtils.saveChartAsJPEG(fileName, chart, width, height);
}
 
Example #27
Source File: ChartExportUtil.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
public static void writeChartToPNG(JFreeChart chart, ChartRenderingInfo info, int width,
    int height, File fileName) throws IOException {
  ChartUtils.saveChartAsPNG(fileName, chart, width, height, info);
}