|
2.5 Example: Off-Screen Image Creation
Since JCCKit 1.1 convenient methods allow easy off-screen image creation.
This is especially useful if you have to create images
on the server of a Web application.
Note, that off-screen image creation needs J2SE 1.4 or higher.
The code below is a small example which takes a properties file (like
this one) and creates
a PNG image of specified size. The important lines of code are
highlighted:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import jcckit.Graphics2DPlotCanvas;
import jcckit.data.DataPlot;
import jcckit.util.ConfigParameters;
import jcckit.util.PropertiesBasedConfigData;
public class ImagePlotter
{
public static void main(String[] args) throws IOException
{
System.getProperties().setProperty("java.awt.headless", "true");
// Handles the commandline argument
if (args.length < 3)
{
System.out.println("Usage: java -cp classycle.jar ImagePlotter "
+ " ");
System.exit(0);
}
String propertiesFile = args[0];
int width = Integer.parseInt(args[1]);
int height = Integer.parseInt(args[2]);
// Sets up a Graphics2DPlotCanvas
ConfigParameters config
= new ConfigParameters(new PropertiesBasedConfigData(propertiesFile));
Graphics2DPlotCanvas plotCanvas = new Graphics2DPlotCanvas(config);
plotCanvas.connect(DataPlot.create(config));
plotCanvas.setDoubleBuffering(false);
// Draws the chart into a off-screen image
BufferedImage image
= new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
plotCanvas.draw2DInto(image);
// Writes the off-screen image into a PNG file
ImageIO.write(image, "png", new File(propertiesFile + ".png"));
}
}
Explanations of the highlighted statements:
- Setting java.awt.headless = true allows to draw
off-screen images on a server without any graphical
window system running. For example, in a Unix environment no X-Server is
needed (but some X libraries might be still necessary).
- Double-buffering has to be switched off. This is possible since
JCCKit 1.1.
- A BufferedImage is an off-screen image.
- The method draw2DInto() of
Graphics2DPlotCanvas draws the chart into the
buffered image as it would be drawn onto the real screen if one runs
Graphics2DPlotCanvas as a Java application
with the specified properties file.
Instead of drawing into a Graphics2D context one can also
draw into a Graphics context by using drawInto()
of
GraphicsPlotCanvas. Note: This only works if
there is no rotated text because rotated texts are
created by double-buffering. In a chart with a
CartesianCoordinateSystem this implies that
the default label of the y-axis has to be removed because it is
a rotated piece of text.
- Since J2SE 1.4 the method ImageIO.write() is a convenient
way to encode images and write them into files.
|