|
| 1 | +package org.scijava.ui.swing.plot.converter; |
| 2 | + |
| 3 | +import org.jfree.chart.JFreeChart; |
| 4 | +import org.scijava.Priority; |
| 5 | +import org.scijava.convert.AbstractConverter; |
| 6 | +import org.scijava.convert.ConversionRequest; |
| 7 | +import org.scijava.convert.ConvertService; |
| 8 | +import org.scijava.convert.Converter; |
| 9 | +import org.scijava.plot.Plot; |
| 10 | +import org.scijava.plugin.Parameter; |
| 11 | +import org.scijava.plugin.Plugin; |
| 12 | + |
| 13 | +import java.awt.geom.Rectangle2D; |
| 14 | +import java.awt.image.BufferedImage; |
| 15 | + |
| 16 | +/** |
| 17 | + * Converter plugin, that converts an {@link Plot} to {@link BufferedImage}. |
| 18 | + * |
| 19 | + * @author Matthias Arzt |
| 20 | + * @see ConvertService |
| 21 | + */ |
| 22 | +@Plugin(type = Converter.class, priority = Priority.NORMAL_PRIORITY) |
| 23 | +public class PlotToBufferedImageConverter extends AbstractConverter<Plot, BufferedImage> |
| 24 | +{ |
| 25 | + |
| 26 | + @Parameter |
| 27 | + ConvertService convertService; |
| 28 | + |
| 29 | + @Override |
| 30 | + public boolean canConvert(ConversionRequest request) { |
| 31 | + return request.destClass().isAssignableFrom( BufferedImage.class ) && |
| 32 | + Plot.class.isAssignableFrom( request.sourceClass() ) && |
| 33 | + convertService.supports(new ConversionRequest( |
| 34 | + request.sourceObject(), request.sourceType(), JFreeChart.class)); |
| 35 | + } |
| 36 | + |
| 37 | + @Override |
| 38 | + public <T> T convert(Object o, Class<T> aClass) { |
| 39 | + if(o instanceof Plot && BufferedImage.class.equals(aClass)) { |
| 40 | + @SuppressWarnings("unchecked") |
| 41 | + T t = (T) toBufferedImage((Plot) o); |
| 42 | + return t; |
| 43 | + } |
| 44 | + return null; |
| 45 | + } |
| 46 | + |
| 47 | + private BufferedImage toBufferedImage(Plot plot) { |
| 48 | + BufferedImage image = new BufferedImage( plot.getPreferredWidth(), plot.getPreferredHeight(), BufferedImage.TYPE_INT_ARGB ); |
| 49 | + JFreeChart chart = convertService.convert(plot, JFreeChart.class); |
| 50 | + chart.draw(image.createGraphics(), new Rectangle2D.Float(0, 0, image.getWidth(), image.getHeight())); |
| 51 | + return image; |
| 52 | + } |
| 53 | + |
| 54 | + @Override |
| 55 | + public Class<BufferedImage> getOutputType() { |
| 56 | + return BufferedImage.class; |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public Class<Plot> getInputType() { |
| 61 | + return Plot.class; |
| 62 | + } |
| 63 | +} |
0 commit comments