View Javadoc

1   /**
2    * This file Copyright (c) 2012 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.templating.jsp.taglib;
35  
36  import java.awt.Color;
37  import java.awt.Font;
38  import java.awt.FontFormatException;
39  import java.awt.FontMetrics;
40  import java.awt.Graphics2D;
41  import java.awt.RenderingHints;
42  import java.awt.font.FontRenderContext;
43  import java.awt.font.TextLayout;
44  import java.awt.geom.Rectangle2D;
45  import java.awt.image.BufferedImage;
46  import java.awt.image.RenderedImage;
47  import java.io.File;
48  import java.io.FileInputStream;
49  import java.io.IOException;
50  import java.io.InputStream;
51  
52  import javax.imageio.ImageIO;
53  
54  
55  /**
56   * Class to generate PNG images from TrueType font strings. Originally by Philip McCarthy - http://chimpen.com
57   * http://chimpen.com/things/archives/001139.php
58   * @author Philip McCarthy
59   * @author Patrick Janssen
60   */
61  public class Text2PngFactory {
62  
63      /** Font name. */
64      private String fontname;
65  
66      /** Font size. */
67      private int fontsize;
68  
69      /** Text to render. */
70      private String text = "";
71  
72      /** Text color. */
73      private int r = 0;
74  
75      private int g = 0;
76  
77      private int b = 0;
78  
79      /** Background colour. */
80      private int br = 0xff;
81  
82      private int bg = 0xff;
83  
84      private int bb = 0xff;
85  
86      /** Used to obtain fontmetrics for given fontname. */
87      private Graphics2D g2;
88  
89      /** Cached Font object. */
90      private Font cachedFont;
91  
92      /**
93       * Construct factory without setting font.
94       */
95      public Text2PngFactory() {
96          // Create a single-pixel buffered image to do font stuff with
97          this.g2 = new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR).createGraphics();
98          // Set same hints as used for final render
99          setOptimalRenderQuality(this.g2);
100     }
101 
102     /**
103      * Construct factory with given font face and size.
104      * @param fontname Name of TrueType font
105      * @param fontsize Point size of font
106      * @throws IOException if font can't be loaded
107      * @throws FontFormatException if font is not a valid TTF
108      */
109     public Text2PngFactory(String fontname, int fontsize) throws IOException, FontFormatException {
110         this(fontname, fontsize, "");
111     }
112 
113     /**
114      * Construct factory with given font face and size.
115      * @param fontname Name of TrueType font
116      * @param fontsize Point size of font
117      * @param text The text to render
118      * @throws IOException if font can't be loaded
119      * @throws FontFormatException if font is not a valid TTF
120      */
121     public Text2PngFactory(String fontname, int fontsize, String text) throws IOException, FontFormatException {
122 
123         // Create a single-pixel buffered image to get font sizes etc from.
124         this.g2 = new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR).createGraphics();
125         // Set same hints as used for final render
126         setOptimalRenderQuality(this.g2);
127         this.setFontFace(fontname);
128         this.setFontSize(fontsize);
129         this.setText(text);
130     }
131 
132     /**
133      * Renders the current text to a .png file.
134      * @param location Location to write the file out to
135      * @throws IOException if file cannot be created
136      */
137     public void createPngFile(String location) throws IOException {
138         createPngFile(new File(location));
139     }
140 
141     /**
142      * Renders the current text to a .png file.
143      * @param location Location to write the file out to
144      * @throws IOException if file cannot be created
145      */
146     public void createPngFile(File location) throws IOException {
147         ImageIO.write(createImage(), "png", location);
148     }
149 
150     /**
151      * Renders the current text in the current font fontname, fontsize and color.
152      * @return Image containing rendered text
153      * @throws IOException if no font name has been specified yet
154      */
155     public RenderedImage createImage() throws IOException {
156 
157         if (this.fontname == null) {
158             throw new IOException("No font name given!");
159         }
160 
161         // Get the bounds needed to render the text
162         FontRenderContext frc = this.g2.getFontRenderContext();
163         TextLayout layout = new TextLayout(this.text, this.cachedFont, frc);
164         Rectangle2D bounds = layout.getBounds();
165 
166         // Get the width needed to render this piece of text
167         // 2 pixels were added here due to problem with cutting of end of text
168         int stringWidth = (int) (Math.ceil(bounds.getWidth())) + 2;
169 
170         // Get the height from generic font info
171         // This way, all strings in this font will have same height
172         // and vertical alignment
173         FontMetrics fm = this.g2.getFontMetrics();
174         int stringHeight = fm.getHeight();
175 
176         // Make an image to contain string
177         BufferedImage im = new BufferedImage(stringWidth, stringHeight, BufferedImage.TYPE_3BYTE_BGR);
178 
179         // Set the font and colours on the image
180         Graphics2D graphics = im.createGraphics();
181 
182         // Setup best-quality rendering
183         setOptimalRenderQuality(graphics);
184 
185         // Set colours and clear rectangle
186         graphics.setBackground(new Color(this.br, this.bg, this.bb));
187         graphics.setColor(new Color(this.r, this.g, this.b));
188         graphics.clearRect(0, 0, stringWidth, stringHeight);
189 
190         // Set the font to use
191         graphics.setFont(getFont());
192 
193         // Position text on baseline, with first character exactly against
194         // left margin
195         layout.draw(graphics, -(float) Math.floor(bounds.getX()), fm.getMaxAscent());
196 
197         // Return the image
198         return im;
199     }
200 
201     /**
202      * Set the text to be rendered by the Txt2PngFactory.
203      * @param text The text to render
204      */
205     public void setText(String text) {
206         this.text = text;
207     }
208 
209     /**
210      * Set 8-bit RGB values for text colour.
211      * @param r Red component (0-255)
212      * @param g Green component (0-255)
213      * @param b Blue component (0-255)
214      */
215     public void setTextRGB(int r, int g, int b) {
216         this.r = r;
217         this.g = g;
218         this.b = b;
219     }
220 
221     /**
222      * Set 8-bit RGB values for background colour.
223      * @param r Red component (0-255)
224      * @param g Green component (0-255)
225      * @param b Blue component (0-255)
226      */
227     public void setBackgroundRGB(int r, int g, int b) {
228         this.br = r;
229         this.bg = g;
230         this.bb = b;
231     }
232 
233     /**
234      * Set the TrueType font to render with.
235      * @param fontname The name of the font to use
236      */
237     public void setFontFace(String fontname) throws IOException, FontFormatException {
238 
239         if (!fontname.equals(this.fontname)) {
240             this.fontname = fontname;
241             updateFace();
242         }
243     }
244 
245     /**
246      * Set the point size of the font.
247      * @param fontsize The point size of the font
248      */
249     public void setFontSize(int fontsize) {
250         if (fontsize != this.fontsize) {
251             this.fontsize = fontsize;
252             updateSize();
253         }
254     }
255 
256     /**
257      * Updates the cached font object.
258      * @throws IOException if the font can't be loaded
259      * @throws FontFormatException if font is not a valid TTF
260      */
261     private void updateFace() throws IOException, FontFormatException {
262         Font createdFont = null;
263 
264         // Attempt to load font from /fonts under classloader
265         String fontpath = "fonts/" + this.fontname + ".ttf";
266 
267         InputStream fontStream = this.getClass().getClassLoader().getResourceAsStream(fontpath);
268         if (fontStream != null) {
269             createdFont = Font.createFont(Font.TRUETYPE_FONT, fontStream);
270             fontStream.close();
271         }
272         // Next try to get it from fontpath
273         if (createdFont == null) {
274             Font tempFont = new Font(this.fontname, Font.PLAIN, 1);
275 
276             // Check we got correct font, not a fallback
277             if (tempFont.getFamily().equals(this.fontname)) {
278                 // It's the correct font, set it
279                 createdFont = tempFont;
280             }
281         }
282         // Last resort, treat as a path to font
283         if (createdFont == null) {
284             fontStream = new FileInputStream(this.fontname);
285 
286             if (fontStream != null) {
287                 createdFont = Font.createFont(Font.TRUETYPE_FONT, fontStream);
288                 fontStream.close();
289             }
290         }
291         // If we still don't have a font, throw exception
292         if (createdFont == null) {
293             throw new IOException("Can't locate font: " + this.fontname);
294         }
295 
296         // Derive font of correct fontsize
297         this.cachedFont = createdFont.deriveFont((float) this.fontsize);
298 
299         // Set on prototype image
300         this.g2.setFont(this.cachedFont);
301     }
302 
303     /**
304      * Updates the cached font to new font derived with new size.
305      */
306     private void updateSize() {
307 
308         if (this.cachedFont == null) {
309             return;
310         }
311 
312         // Derive font of correct fontsize
313         this.cachedFont = this.cachedFont.deriveFont((float) this.fontsize);
314 
315         // Set on Graphics object so we can get FontMetrics
316         this.g2.setFont(this.cachedFont);
317     }
318 
319     /**
320      * Get the FontMetrics object for the current font.
321      * @return FontMetrics object for current font
322      */
323     private FontMetrics getFontMetrics() {
324 
325         return this.g2.getFontMetrics();
326     }
327 
328     /**
329      * Get a Font object for the current fontname and fontsize.
330      * @return Font object for current name and size
331      */
332     private Font getFont() {
333 
334         return this.cachedFont;
335     }
336 
337     /**
338      * Sets rendering hints for optimal rendering quality.
339      * @param graphics Graphics2D object to set rendering options on
340      */
341     private void setOptimalRenderQuality(Graphics2D graphics) {
342 
343         graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
344         graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
345         graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
346         graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
347     }
348 
349     @Override
350     public String toString() {
351         return this.fontname + ", " + this.fontsize + "pt: " + this.text;
352     }
353 }