View Javadoc
1   /**
2    * This file Copyright (c) 2012-2016 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   */
59  public class Text2PngFactory {
60  
61      /** Font name. */
62      private String fontname;
63  
64      /** Font size. */
65      private int fontsize;
66  
67      /** Text to render. */
68      private String text = "";
69  
70      /** Text color. */
71      private int r = 0;
72  
73      private int g = 0;
74  
75      private int b = 0;
76  
77      /** Background colour. */
78      private int br = 0xff;
79  
80      private int bg = 0xff;
81  
82      private int bb = 0xff;
83  
84      /** Used to obtain fontmetrics for given fontname. */
85      private Graphics2D g2;
86  
87      /** Cached Font object. */
88      private Font cachedFont;
89  
90      /**
91       * Construct factory without setting font.
92       */
93      public Text2PngFactory() {
94          // Create a single-pixel buffered image to do font stuff with
95          this.g2 = new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR).createGraphics();
96          // Set same hints as used for final render
97          setOptimalRenderQuality(this.g2);
98      }
99  
100     /**
101      * Construct factory with given font face and size.
102      * @param fontname Name of TrueType font
103      * @param fontsize Point size of font
104      * @throws IOException if font can't be loaded
105      * @throws FontFormatException if font is not a valid TTF
106      */
107     public Text2PngFactory(String fontname, int fontsize) throws IOException, FontFormatException {
108         this(fontname, fontsize, "");
109     }
110 
111     /**
112      * Construct factory with given font face and size.
113      * @param fontname Name of TrueType font
114      * @param fontsize Point size of font
115      * @param text The text to render
116      * @throws IOException if font can't be loaded
117      * @throws FontFormatException if font is not a valid TTF
118      */
119     public Text2PngFactory(String fontname, int fontsize, String text) throws IOException, FontFormatException {
120 
121         // Create a single-pixel buffered image to get font sizes etc from.
122         this.g2 = new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR).createGraphics();
123         // Set same hints as used for final render
124         setOptimalRenderQuality(this.g2);
125         this.setFontFace(fontname);
126         this.setFontSize(fontsize);
127         this.setText(text);
128     }
129 
130     /**
131      * Renders the current text to a .png file.
132      * @param location Location to write the file out to
133      * @throws IOException if file cannot be created
134      */
135     public void createPngFile(String location) throws IOException {
136         createPngFile(new File(location));
137     }
138 
139     /**
140      * Renders the current text to a .png file.
141      * @param location Location to write the file out to
142      * @throws IOException if file cannot be created
143      */
144     public void createPngFile(File location) throws IOException {
145         ImageIO.write(createImage(), "png", location);
146     }
147 
148     /**
149      * Renders the current text in the current font fontname, fontsize and color.
150      * @return Image containing rendered text
151      * @throws IOException if no font name has been specified yet
152      */
153     public RenderedImage createImage() throws IOException {
154 
155         if (this.fontname == null) {
156             throw new IOException("No font name given!");
157         }
158 
159         // Get the bounds needed to render the text
160         FontRenderContext frc = this.g2.getFontRenderContext();
161         TextLayout layout = new TextLayout(this.text, this.cachedFont, frc);
162         Rectangle2D bounds = layout.getBounds();
163 
164         // Get the width needed to render this piece of text
165         // 2 pixels were added here due to problem with cutting of end of text
166         int stringWidth = (int) (Math.ceil(bounds.getWidth())) + 2;
167 
168         // Get the height from generic font info
169         // This way, all strings in this font will have same height
170         // and vertical alignment
171         FontMetrics fm = this.g2.getFontMetrics();
172         int stringHeight = fm.getHeight();
173 
174         // Make an image to contain string
175         BufferedImage im = new BufferedImage(stringWidth, stringHeight, BufferedImage.TYPE_3BYTE_BGR);
176 
177         // Set the font and colours on the image
178         Graphics2D graphics = im.createGraphics();
179 
180         // Setup best-quality rendering
181         setOptimalRenderQuality(graphics);
182 
183         // Set colours and clear rectangle
184         graphics.setBackground(new Color(this.br, this.bg, this.bb));
185         graphics.setColor(new Color(this.r, this.g, this.b));
186         graphics.clearRect(0, 0, stringWidth, stringHeight);
187 
188         // Set the font to use
189         graphics.setFont(getFont());
190 
191         // Position text on baseline, with first character exactly against
192         // left margin
193         layout.draw(graphics, -(float) Math.floor(bounds.getX()), fm.getMaxAscent());
194 
195         // Return the image
196         return im;
197     }
198 
199     /**
200      * Set the text to be rendered by the Txt2PngFactory.
201      * @param text The text to render
202      */
203     public void setText(String text) {
204         this.text = text;
205     }
206 
207     /**
208      * Set 8-bit RGB values for text colour.
209      * @param r Red component (0-255)
210      * @param g Green component (0-255)
211      * @param b Blue component (0-255)
212      */
213     public void setTextRGB(int r, int g, int b) {
214         this.r = r;
215         this.g = g;
216         this.b = b;
217     }
218 
219     /**
220      * Set 8-bit RGB values for background colour.
221      * @param r Red component (0-255)
222      * @param g Green component (0-255)
223      * @param b Blue component (0-255)
224      */
225     public void setBackgroundRGB(int r, int g, int b) {
226         this.br = r;
227         this.bg = g;
228         this.bb = b;
229     }
230 
231     /**
232      * Set the TrueType font to render with.
233      * @param fontname The name of the font to use
234      */
235     public void setFontFace(String fontname) throws IOException, FontFormatException {
236 
237         if (!fontname.equals(this.fontname)) {
238             this.fontname = fontname;
239             updateFace();
240         }
241     }
242 
243     /**
244      * Set the point size of the font.
245      * @param fontsize The point size of the font
246      */
247     public void setFontSize(int fontsize) {
248         if (fontsize != this.fontsize) {
249             this.fontsize = fontsize;
250             updateSize();
251         }
252     }
253 
254     /**
255      * Updates the cached font object.
256      * @throws IOException if the font can't be loaded
257      * @throws FontFormatException if font is not a valid TTF
258      */
259     private void updateFace() throws IOException, FontFormatException {
260         Font createdFont = null;
261 
262         // Attempt to load font from /fonts under classloader
263         String fontpath = "fonts/" + this.fontname + ".ttf";
264 
265         InputStream fontStream = this.getClass().getClassLoader().getResourceAsStream(fontpath);
266         if (fontStream != null) {
267             createdFont = Font.createFont(Font.TRUETYPE_FONT, fontStream);
268             fontStream.close();
269         }
270         // Next try to get it from fontpath
271         if (createdFont == null) {
272             Font tempFont = new Font(this.fontname, Font.PLAIN, 1);
273 
274             // Check we got correct font, not a fallback
275             if (tempFont.getFamily().equals(this.fontname)) {
276                 // It's the correct font, set it
277                 createdFont = tempFont;
278             }
279         }
280         // Last resort, treat as a path to font
281         if (createdFont == null) {
282             fontStream = new FileInputStream(this.fontname);
283             createdFont = Font.createFont(Font.TRUETYPE_FONT, fontStream);
284             fontStream.close();
285         }
286         // If we still don't have a font, throw exception
287         if (createdFont == null) {
288             throw new IOException("Can't locate font: " + this.fontname);
289         }
290 
291         // Derive font of correct fontsize
292         this.cachedFont = createdFont.deriveFont((float) this.fontsize);
293 
294         // Set on prototype image
295         this.g2.setFont(this.cachedFont);
296     }
297 
298     /**
299      * Updates the cached font to new font derived with new size.
300      */
301     private void updateSize() {
302 
303         if (this.cachedFont == null) {
304             return;
305         }
306 
307         // Derive font of correct fontsize
308         this.cachedFont = this.cachedFont.deriveFont((float) this.fontsize);
309 
310         // Set on Graphics object so we can get FontMetrics
311         this.g2.setFont(this.cachedFont);
312     }
313 
314     /**
315      * Get the FontMetrics object for the current font.
316      * @return FontMetrics object for current font
317      */
318     private FontMetrics getFontMetrics() {
319 
320         return this.g2.getFontMetrics();
321     }
322 
323     /**
324      * Get a Font object for the current fontname and fontsize.
325      * @return Font object for current name and size
326      */
327     private Font getFont() {
328 
329         return this.cachedFont;
330     }
331 
332     /**
333      * Sets rendering hints for optimal rendering quality.
334      * @param graphics Graphics2D object to set rendering options on
335      */
336     private void setOptimalRenderQuality(Graphics2D graphics) {
337 
338         graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
339         graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
340         graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
341         graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
342     }
343 
344     @Override
345     public String toString() {
346         return this.fontname + ", " + this.fontsize + "pt: " + this.text;
347     }
348 }