1 package com.stateofflow.eclipse.metrics.export.html.histogram;
2
3 import java.awt.Graphics2D;
4 import java.awt.geom.Rectangle2D;
5 import java.awt.image.BufferedImage;
6 import java.io.File;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.io.OutputStream;
10
11 import org.jfree.chart.ChartFactory;
12 import org.jfree.chart.JFreeChart;
13
14 import com.stateofflow.eclipse.metrics.collator.MetricsCollator;
15 import com.stateofflow.eclipse.metrics.metric.MetricId;
16 import com.sun.image.codec.jpeg.ImageFormatException;
17 import com.sun.image.codec.jpeg.JPEGCodec;
18 import com.sun.image.codec.jpeg.JPEGEncodeParam;
19 import com.sun.image.codec.jpeg.JPEGImageEncoder;
20
21 public final class JpegProducer {
22 private static final int IMAGE_WIDTH = 800;
23 private static final int IMAGE_HEIGHT = 500;
24
25 private final HistogramFactory factory;
26
27 public JpegProducer(final HistogramFactory factory) {
28 this.factory = factory;
29 }
30
31 private void paintImage(final Graphics2D graphics, final MetricsCollator collator, final MetricId metricId) {
32 final String presentationName = factory.getPresentations().getPresentationName(metricId);
33
34 final JFreeChart chart = ChartFactory.createStackedVerticalBarChart(presentationName, presentationName, "Occurrences", factory.createMetricsDataset(collator, metricId), true, false, false);
35 chart.draw(graphics, new Rectangle2D.Double(0, 0, JpegProducer.IMAGE_WIDTH, JpegProducer.IMAGE_HEIGHT));
36 }
37
38 public void produce(final File file, final MetricsCollator collator, final MetricId metricId) throws IOException {
39 final BufferedImage image = new BufferedImage(JpegProducer.IMAGE_WIDTH, JpegProducer.IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
40 paintImage((Graphics2D) image.getGraphics(), collator, metricId);
41 saveImage(file, image);
42 image.getGraphics().dispose();
43 }
44
45 private void saveImage(final File file, final BufferedImage image) throws ImageFormatException, IOException {
46 if (file.exists()) {
47 file.delete();
48 }
49 final OutputStream out = new FileOutputStream(file);
50 final JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
51 final JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
52 param.setQuality(1, true);
53 encoder.encode(image, param);
54 out.close();
55 }
56 }
57