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