Example usage for org.jfree.chart.encoders KeypointPNGEncoderAdapter KeypointPNGEncoderAdapter

List of usage examples for org.jfree.chart.encoders KeypointPNGEncoderAdapter KeypointPNGEncoderAdapter

Introduction

In this page you can find the example usage for org.jfree.chart.encoders KeypointPNGEncoderAdapter KeypointPNGEncoderAdapter.

Prototype

KeypointPNGEncoderAdapter

Source Link

Usage

From source file:org.gbif.portal.web.util.ChartUtils.java

/**
 * Writes out the image using the supplied file name.
 * //from   ww w .  ja  v  a2s  .c o  m
 * @param legend
 * @param fileName
 * @return
 */
public static String writePieChartImageToTempFile(Map<String, Double> legend, String fileName) {

    String filePath = System.getProperty(tmpDirSystemProperty) + File.separator + fileName + defaultExtension;
    File fileToCheck = new File(filePath);
    if (fileToCheck.exists()) {
        return fileName + defaultExtension;
    }

    final DefaultPieDataset data = new DefaultPieDataset();
    Set<String> keys = legend.keySet();
    for (String key : keys) {
        logger.info("Adding key : " + key);
        data.setValue(key, legend.get(key));
    }

    // create a pie chart...
    final boolean withLegend = true;
    final JFreeChart chart = ChartFactory.createPieChart(null, data, withLegend, false, false);

    PiePlot piePlot = (PiePlot) chart.getPlot();
    piePlot.setLabelFont(new Font("Arial", Font.PLAIN, 10));
    piePlot.setLabelBackgroundPaint(Color.WHITE);

    LegendTitle lt = chart.getLegend();
    lt.setBackgroundPaint(Color.WHITE);
    lt.setWidth(300);
    lt.setBorder(0, 0, 0, 0);
    lt.setItemFont(new Font("Arial", Font.PLAIN, 11));

    chart.setPadding(new RectangleInsets(0, 0, 0, 0));
    chart.setBorderVisible(false);
    chart.setBackgroundImageAlpha(0);
    chart.setBackgroundPaint(Color.WHITE);
    chart.setBorderPaint(Color.LIGHT_GRAY);

    final BufferedImage image = new BufferedImage(300, 250, BufferedImage.TYPE_INT_RGB);
    KeypointPNGEncoderAdapter adapter = new KeypointPNGEncoderAdapter();
    adapter.setQuality(1);
    try {
        adapter.encode(image);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    final Graphics2D g2 = image.createGraphics();
    g2.setFont(new Font("Arial", Font.PLAIN, 11));
    final Rectangle2D chartArea = new Rectangle2D.Double(0, 0, 300, 250);

    // draw
    chart.draw(g2, chartArea, null, null);

    try {
        FileOutputStream fOut = new FileOutputStream(fileToCheck);
        ChartUtilities.writeChartAsPNG(fOut, chart, 300, 250);
        return fileToCheck.getName();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        return null;
    }
}

From source file:org.sonar.server.charts.ChartsServlet.java

private void exportAsPNG(BufferedImage image, OutputStream out) throws IOException {
    KeypointPNGEncoderAdapter encoder = new KeypointPNGEncoderAdapter();
    encoder.setEncodingAlpha(true);//  ww w  .ja  v a 2 s  . c o  m
    encoder.encode(image, out);
}

From source file:org.sonar.server.charts.deprecated.BaseChart.java

public void exportChartAsPNG(OutputStream out) throws IOException {
    KeypointPNGEncoderAdapter encoder = new KeypointPNGEncoderAdapter();
    encoder.setEncodingAlpha(true);// w  w  w . ja va  2 s . c  o  m
    encoder.encode(getChartImage(), out);
}

From source file:org.jivesoftware.openfire.reporting.graph.GraphEngine.java

/**
 * Creates a graph in PNG format.  The PNG graph is encoded by the KeypointPNGEncoderAdapter
 * so that the resulting PNG is encoded with alpha transparency.
 *
 * @param key/*  ww  w .  j a  v a  2s. c o m*/
 * @param width
 * @param height
 * @param startTime
 * @param endTime
 * @param dataPoints
 * @return
 * @throws IOException
 */
public byte[] generateGraph(String key, int width, int height, String color, long startTime, long endTime,
        int dataPoints) throws IOException {

    JFreeChart chart = generateChart(key, width, height, color, startTime, endTime, dataPoints);
    KeypointPNGEncoderAdapter encoder = new KeypointPNGEncoderAdapter();
    encoder.setEncodingAlpha(true);
    return encoder.encode(chart.createBufferedImage(width, height, BufferedImage.BITMASK, null));
}

From source file:au.edu.jcu.kepler.hydrant.JFreeChartPlot.java

public synchronized void fillPlot() {
    ReplacementManager man = ReplacementUtils.getReplacementManager(_plotterBase);
    HashMap data_map = new HashMap();
    String fullName = _plotterBase.getFullName();
    data_map.put("name", fullName);
    data_map.put("type", "IMAGE");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    KeypointPNGEncoderAdapter encoder = new KeypointPNGEncoderAdapter();
    try {//w  ww. j av  a2  s.co m
        encoder.encode(_chart.createBufferedImage(480, 300), baos);

    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    data_map.put("plotOutput", baos);
    data_map.put("format", "png");
    //data_map.put("output", file.getAbsolutePath());
    man.writeData(data_map);
}

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;/*  w w  w .  j a v  a  2s . co m*/
    } 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:org.jivesoftware.openfire.reporting.graph.GraphEngine.java

/**
 * Generates a Sparkline type graph. Sparkline graphs
 * are "intense, simple, wordlike graphics" so named by Edward Tufte. The big
 * difference between the graph produced by this method compared to the
 * graph produced by the <code>generateGraph</code> method is that this one
 * produces graphs with no x-axis and no y-axis and is usually smaller in size.
 * @param key/*from  w  w  w  . j  a v  a2s  . com*/
 * @param width
 * @param height
 * @param startTime
 * @param endTime
 * @param dataPoints
 * @return
 * @throws IOException
 */
public byte[] generateSparklinesGraph(String key, int width, int height, String color, long startTime,
        long endTime, int dataPoints) throws IOException {
    Statistic[] def = statsViewer.getStatistic(key);
    if (def == null) {
        return null;
    }

    JFreeChart chart;
    switch (def[0].getStatType()) {
    case count:
        chart = generateSparklineBarGraph(key, color, def, startTime, endTime, dataPoints);
        break;
    default:
        chart = generateSparklineAreaChart(key, color, def, startTime, endTime, dataPoints);
    }

    KeypointPNGEncoderAdapter encoder = new KeypointPNGEncoderAdapter();
    encoder.setEncodingAlpha(true);
    return encoder.encode(chart.createBufferedImage(width, height, BufferedImage.BITMASK, null));
}

From source file:edu.jhuapl.graphs.jfreechart.JFreeChartBaseSource.java

private static ImageEncoder getEncoder(Encoding encoding) throws GraphException {
    switch (encoding) {
    case JPEG:/*from   ww w  . ja v a 2  s.c om*/
        return ImageEncoderFactory.newInstance("jpeg");
    case PNG:
        return ImageEncoderFactory.newInstance("png");
    case PNG_WITH_TRANSPARENCY:
        //this is noted as being slower for big graphs
        KeypointPNGEncoderAdapter keypointPNGEncoderAdapter = new KeypointPNGEncoderAdapter();
        keypointPNGEncoderAdapter.setEncodingAlpha(true);
        return keypointPNGEncoderAdapter;
    default:
        throw new GraphException("Unrecognized encoding \"" + encoding.toString() + "\"");
    }
}

From source file:org.gbif.portal.web.controller.dataset.IndexingHistoryController.java

/**
 * Create a time series graphic to display indexing processes.
 * /*from   ww w .  ja v a  2s  .c  o m*/
 * @param dataProvider
 * @param dataResource
 * @param activities
 * @param fileNamePrefix
 * @return
 */
public String timeSeriesTest(DataProviderDTO dataProvider, DataResourceDTO dataResource,
        List<LoggedActivityDTO> loggedActivities, String fileNamePrefix, int minProcessingTimeToRender) {

    List<LoggedActivityDTO> activities = new ArrayList<LoggedActivityDTO>();
    for (LoggedActivityDTO la : loggedActivities) {
        if (la.getDataResourceKey() != null && la.getDataResourceName() != null && la.getEventName() != null)
            activities.add(la);
    }

    //if no activities to render, return
    if (activities.isEmpty())
        return null;

    Map<String, Integer> drActualCount = new HashMap<String, Integer>();
    Map<String, Integer> drCount = new HashMap<String, Integer>();

    //record the actual counts
    for (LoggedActivityDTO laDTO : activities) {
        if (laDTO.getStartDate() != null && laDTO.getEndDate() != null
                && laDTO.getDurationInMillisecs() > minProcessingTimeToRender) {
            if (drActualCount.get(laDTO.getDataResourceName()) == null) {
                drActualCount.put(laDTO.getDataResourceName(), new Integer(4));
                drCount.put(laDTO.getDataResourceName(), new Integer(0));
            } else {
                Integer theCount = drActualCount.get(laDTO.getDataResourceName());
                theCount = new Integer(theCount.intValue() + 4);
                drActualCount.remove(laDTO.getDataResourceName());
                drActualCount.put(laDTO.getDataResourceName(), theCount);
            }
        }
    }

    StringBuffer fileNameBuffer = new StringBuffer(fileNamePrefix);
    if (dataResource != null) {
        fileNameBuffer.append("-resource-");
        fileNameBuffer.append(dataResource.getKey());
    } else if (dataProvider != null) {
        fileNameBuffer.append("-provider-");
        fileNameBuffer.append(dataProvider.getKey());
    }
    fileNameBuffer.append(".png");

    String fileName = fileNameBuffer.toString();
    String filePath = System.getProperty("java.io.tmpdir") + File.separator + fileName;

    File fileToCheck = new File(filePath);
    if (fileToCheck.exists()) {
        return fileName;
    }

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    boolean generateChart = false;

    int count = 1;
    int dataResourceCount = 1;

    Collections.sort(activities, new Comparator<LoggedActivityDTO>() {
        public int compare(LoggedActivityDTO o1, LoggedActivityDTO o2) {
            if (o1 == null || o2 == null || o1.getDataResourceKey() != null || o2.getDataResourceKey() != null)
                return -1;
            return o1.getDataResourceKey().compareTo(o2.getDataResourceKey());
        }
    });

    String currentDataResourceKey = activities.get(0).getDataResourceKey();

    for (LoggedActivityDTO laDTO : activities) {
        if (laDTO.getStartDate() != null && laDTO.getEndDate() != null
                && laDTO.getDurationInMillisecs() > minProcessingTimeToRender) {

            if (currentDataResourceKey != null && !currentDataResourceKey.equals(laDTO.getDataResourceKey())) {
                dataResourceCount++;
                count = count + 1;
                currentDataResourceKey = laDTO.getDataResourceKey();
            }
            TimeSeries s1 = new TimeSeries(laDTO.getDataResourceName(), "Process time period",
                    laDTO.getEventName(), Hour.class);
            s1.add(new Hour(laDTO.getStartDate()), count);
            s1.add(new Hour(laDTO.getEndDate()), count);
            dataset.addSeries(s1);
            generateChart = true;
        }
    }

    if (!generateChart)
        return null;

    // create a pie chart...
    final JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false);

    XYPlot plot = chart.getXYPlot();
    plot.setWeight(10);
    plot.getRangeAxis().setAutoRange(false);
    plot.getRangeAxis().setRange(0, drCount.size() + 1);
    plot.getRangeAxis().setAxisLineVisible(false);
    plot.getRangeAxis().setAxisLinePaint(Color.WHITE);
    plot.setDomainCrosshairValue(1);
    plot.setRangeGridlinesVisible(false);
    plot.getRangeAxis().setVisible(false);
    plot.getRangeAxis().setLabel("datasets");

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setItemLabelsVisible(true);
    MyXYItemLabelGenerator labelGenerator = new MyXYItemLabelGenerator();
    labelGenerator.setDataResourceActualCount(drActualCount);
    labelGenerator.setDataResourceCount(drCount);
    renderer.setItemLabelGenerator(labelGenerator);

    List<TimeSeries> seriesList = dataset.getSeries();
    for (TimeSeries series : seriesList) {
        if (((String) series.getRangeDescription()).startsWith("extraction")) {
            renderer.setSeriesPaint(seriesList.indexOf(series), Color.RED);
        } else {
            renderer.setSeriesPaint(seriesList.indexOf(series), Color.BLUE);
        }
        renderer.setSeriesStroke(seriesList.indexOf(series), new BasicStroke(7f));
    }

    int imageHeight = 30 * dataResourceCount;
    if (imageHeight < 100) {
        imageHeight = 100;
    } else {
        imageHeight = imageHeight + 100;
    }

    final BufferedImage image = new BufferedImage(900, imageHeight, BufferedImage.TYPE_INT_RGB);
    KeypointPNGEncoderAdapter adapter = new KeypointPNGEncoderAdapter();
    adapter.setQuality(1);
    try {
        adapter.encode(image);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    final Graphics2D g2 = image.createGraphics();
    g2.setFont(new Font("Arial", Font.PLAIN, 11));
    final Rectangle2D chartArea = new Rectangle2D.Double(0, 0, 900, imageHeight);

    // draw
    chart.draw(g2, chartArea, null, null);

    //styling
    chart.setPadding(new RectangleInsets(0, 0, 0, 0));
    chart.setBorderVisible(false);
    chart.setBackgroundImageAlpha(0);
    chart.setBackgroundPaint(Color.WHITE);
    chart.setBorderPaint(Color.LIGHT_GRAY);

    try {
        FileOutputStream fOut = new FileOutputStream(filePath);
        ChartUtilities.writeChartAsPNG(fOut, chart, 900, imageHeight);
        return fileName;
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:userinterface.graph.Graph.java

/**
 * Renders the current graph to a JPEG file.
 * //from w w  w .j a v  a 2s  .c o  m
 * @param file
 *             The file to export the JPEG data to.
 * @throws GraphException, IOException
 *             If file cannot be written to.
 */
public void exportToPNG(File file, int width, int height, boolean alpha) throws GraphException, IOException {

    FileOutputStream fileOutputStream = new FileOutputStream(file);

    KeypointPNGEncoderAdapter encoder = new KeypointPNGEncoderAdapter();
    encoder.setEncodingAlpha(alpha);

    Paint bgPaint = chart.getBackgroundPaint();

    if (alpha) {
        chart.setBackgroundPaint(null);
    }

    BufferedImage bufferedImage = chart.createBufferedImage(width, height,
            alpha ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB, null);

    if (alpha) {
        chart.setBackgroundPaint(bgPaint);
    }

    encoder.encode(bufferedImage, fileOutputStream);

    fileOutputStream.flush();
    fileOutputStream.close();

    //ChartUtilities.saveChartAsPNG(file, this.chart, width, height, null, alpha, 9);
}