1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.millscript.millscript.render;
22
23 import org.millscript.commons.alert.Alert;
24 import org.millscript.commons.vfs.VFile;
25 import org.millscript.millscript.alert.Alerts;
26 import org.millscript.millscript.datatypes.Image;
27
28 import java.awt.image.BufferedImage;
29 import java.io.IOException;
30 import java.io.OutputStream;
31
32 import javax.imageio.ImageWriter;
33 import javax.imageio.stream.MemoryCacheImageOutputStream;
34
35 /**
36 * This is the parent of all image renderers in MillScript. Subclasses simply
37 * need to set the relevant image writer and SVG transcoder.
38 */
39 public abstract class ImageRender {
40
41 /**
42 * The image writer to use when writing out a raster image.
43 */
44 private ImageWriter imageWriter;
45
46 /**
47 * Renders the specified image to the specified output file.
48 *
49 * @param image the image to render to the output
50 * @param outFile the virtual file to render the image to
51 */
52 public void renderImage( final Image image, final VFile outFile ) {
53 try {
54 OutputStream ostream = outFile.getOutputStream();
55 this.renderImageToStream( image, ostream );
56 ostream.flush();
57 ostream.close();
58 } catch ( Alert ex ) {
59 throw(
60 ex.culprit( "file", outFile ).remishap()
61 );
62 } catch ( IOException ex ) {
63 throw(
64 Alerts.eval(
65 "Problem writing to output file",
66 null
67 ).culprit( "file", outFile ).culprit( "message", ex.getMessage() ).mishap()
68 );
69 }
70 }
71
72 /**
73 * Renders the specified image to the specified output stream. This method
74 * is overriden to support SVG images.
75 *
76 * @param image the image to render
77 * @param ostream the output to render to
78 * @throws IOException thrown if an IO error occurs
79 */
80 public void renderImageToStream( final Image image, final OutputStream ostream ) throws IOException {
81 image.renderAsRasterToStream( ostream, this );
82 }
83
84 /**
85 * Sets this image renderers raster image writer.
86 *
87 * @param i the image writer to use for rasterising an image
88 */
89 final void setImageWriter( final ImageWriter i ) {
90 this.imageWriter = i;
91 }
92
93 /**
94 * Performs the general writing step from the specified image to the specified output.
95 *
96 * @param image the image to write
97 * @param ostream the output stream to write to
98 * @throws IOException thrown if any IO problems occur
99 */
100 public final void write( final BufferedImage image, final OutputStream ostream ) throws IOException {
101 this.imageWriter.setOutput( new MemoryCacheImageOutputStream( ostream ) );
102 imageWriter.write( image );
103 imageWriter.reset();
104 }
105
106 }