KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > infoglue > deliver > util > graphics > ImageRenderer


1 /* ===============================================================================
2  *
3  * Part of the InfoGlue Content Management Platform (www.infoglue.org)
4  *
5  * ===============================================================================
6  *
7  * Copyright (C)
8  *
9  * This program is free software; you can redistribute it and/or modify it under
10  * the terms of the GNU General Public License version 2, as published by the
11  * Free Software Foundation. See the file LICENSE.html for more information.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
19  * Place, Suite 330 / Boston, MA 02111-1307 / USA.
20  *
21  * ===============================================================================
22  */

23
24 package org.infoglue.deliver.util.graphics;
25
26 import java.awt.Color JavaDoc;
27 import java.awt.Font JavaDoc;
28 import java.awt.Graphics2D JavaDoc;
29 import java.awt.RenderingHints JavaDoc;
30 import java.awt.font.TextAttribute JavaDoc;
31 import java.awt.font.TextLayout JavaDoc;
32 import java.awt.image.BufferedImage JavaDoc;
33 import java.io.File JavaDoc;
34 import java.net.URL JavaDoc;
35 import java.text.AttributedCharacterIterator JavaDoc;
36 import java.text.AttributedString JavaDoc;
37 import java.util.ArrayList JavaDoc;
38 import java.util.Hashtable JavaDoc;
39 import java.util.Iterator JavaDoc;
40 import java.util.StringTokenizer JavaDoc;
41 import java.util.Vector JavaDoc;
42
43 import javax.imageio.ImageIO JavaDoc;
44
45
46 /**
47  * This class demonstrates how to line-break and draw a paragraph
48  * of text using LineBreakMeasurer and TextLayout.
49  *
50  * This class constructs a LineBreakMeasurer from an
51  * AttributedCharacterIterator. It uses the LineBreakMeasurer
52  * to create and draw TextLayouts (lines of text) which fit within
53  * the Component's width.
54  */

55
56 public class ImageRenderer //extends JFrame
57
{
58     public static final int ALIGN_LEFT = 0;
59     public static final int ALIGN_CENTER = 1;
60     public static final int ALIGN_RIGHT = 2;
61
62     private int canvasWidth = 300;
63     private int canvasHeight = 100;
64     private int textStartPosX = 5;
65     private int textStartPosY = 25;
66     private int textWidth = 300;
67     private int textHeight = 100;
68     
69     private String JavaDoc fontName = "Dialog";
70     private int fontStyle = Font.PLAIN;
71     private int fontSize = 12;
72     
73     private int alignment = ALIGN_LEFT;
74         
75     private Color JavaDoc backgroundColor = null;
76     private Color JavaDoc foreGroundColor = null;
77     
78     private String JavaDoc backgroundImageUrl = null;
79     
80     /*
81     Frame frame = null;
82     
83     public static void main(String[] args)
84     {
85         ImageRenderer ir = new ImageRenderer();
86         
87         ir.setCanvasWidth(300);
88         ir.setCanvasHeight(100);
89         ir.setTextStartPosX(5);
90         ir.setTextStartPosY(25);
91         ir.setTextWidth(300);
92         ir.setTextHeight(100);
93         ir.setAlignment(ALIGN_RIGHT);
94         
95         ir.setFontName("Verdana");
96         ir.setFontStyle(Font.BOLD);
97         ir.setFontSize(20);
98         
99         ir.setForeGroundColor(Color.BLACK);
100         ir.setBackgroundColor(Color.WHITE);
101         //ir.setBackgroundImageUrl("http://localhost:8080/infoglueDeliverDev/digitalAssets/94_1080909656343_gradient.jpg");
102         
103         //ir.listAvailableFonts();
104         ir.setSize(400, 400);
105         ir.setVisible(true);
106     }
107
108     private void listAvailableFonts()
109     {
110         GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
111         String[] fontNames = env.getAvailableFontFamilyNames();
112         //logger.info("Available Fonts:");
113         for(int i=0; i<fontNames.length; i++)
114         {
115             //logger.info(" " + fontNames[i]);
116             System.out.println(" " + fontNames[i]);
117         }
118     }
119
120     
121     public void paint(Graphics g)
122     {
123         Graphics2D g2d = (Graphics2D)g;
124         
125         try
126         {
127             drawText(g2d, "Detta är ett test som bör brytas");
128
129         }
130         catch(Exception e)
131         {
132             e.printStackTrace();
133         }
134     }
135     
136
137     public ImageRenderer()
138     {
139         //frame = new Frame();
140         //frame.addNotify();
141     }
142     */

143     
144     /**
145      * This method generates a gif-image from the send in string with the given width/height.
146      */

147
148     public void generateGifImageFromText(String JavaDoc file, String JavaDoc text, String JavaDoc encoding) throws Exception JavaDoc
149     {
150         BufferedImage JavaDoc image = new BufferedImage JavaDoc(this.canvasWidth, this.canvasHeight, BufferedImage.TYPE_INT_ARGB);
151         
152         //if(!encoding.equalsIgnoreCase("utf-8"))
153
// text = new String(text.getBytes(encoding), "UTF-8");
154

155         drawText((Graphics2D JavaDoc)image.getGraphics(), text);
156         Hashtable JavaDoc arguments = new Hashtable JavaDoc();
157         arguments.put("encoding", "websafe");
158         //logger.info("Going to generate gif to disc...");
159
//new GifEncoder().encode(image, new DataOutputStream(new FileOutputStream(file)), arguments);
160
File JavaDoc outputFile = new File JavaDoc(file);
161         javax.imageio.ImageIO.write(image, "PNG", outputFile);
162     }
163
164
165     private void drawText(Graphics2D JavaDoc g2d, String JavaDoc text) throws Exception JavaDoc
166     {
167         Font JavaDoc font = FontSaver.create(this.fontName, this.fontStyle, this.fontSize);
168
169         if(this.backgroundImageUrl != null)
170         {
171             URL JavaDoc url = new URL JavaDoc(this.backgroundImageUrl);
172             BufferedImage JavaDoc bufferedImage = ImageIO.read(url);
173             g2d.drawImage(bufferedImage,0,0, null);
174         }
175         else
176         {
177             g2d.setBackground(this.backgroundColor);
178             g2d.setPaint(this.backgroundColor);
179             g2d.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
180         }
181         
182         g2d.setPaint(this.foreGroundColor);
183         g2d.setFont(font);
184         
185         g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
186         g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
187         
188         AttributedString JavaDoc as = new AttributedString JavaDoc(text);
189         as.addAttribute(TextAttribute.FONT, font);
190         as.addAttribute(TextAttribute.JUSTIFICATION, font);
191         AttributedCharacterIterator JavaDoc paragraph = as.getIterator();
192         int paragraphStart = paragraph.getBeginIndex();
193         int paragraphEnd = paragraph.getEndIndex();
194                 
195         float drawPosY = (float)textStartPosY;
196
197         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(text);
198         Vector JavaDoc v = new Vector JavaDoc();
199         while(st.hasMoreElements())
200         {
201             String JavaDoc word = (String JavaDoc)st.nextElement();
202             v.addElement(word);
203         }
204         
205         String JavaDoc testString = "";
206         String JavaDoc realString = "";
207         java.util.List JavaDoc lines = new ArrayList JavaDoc();
208         int offset = 0;
209         for(int i=0; i < v.size(); i++)
210         {
211             testString = realString + (String JavaDoc)v.get(i) + " ";
212             TextLayout JavaDoc testLay = new TextLayout JavaDoc(testString, font, g2d.getFontRenderContext());
213              
214             if(testLay.getBounds().getWidth() > textWidth || i == v.size()-2)
215             {
216                 String JavaDoc remainingString = testString;
217                 if(v.size() > i + 1)
218                     remainingString += (String JavaDoc)v.get(i + 1);
219                 if(v.size() > i + 2)
220                     remainingString += " " + (String JavaDoc)v.get(i + 2);
221                 
222                 TextLayout JavaDoc fullyFilledLay = new TextLayout JavaDoc(remainingString, font, g2d.getFontRenderContext());
223                 if(fullyFilledLay.getBounds().getWidth() < textWidth)
224                 {
225                     realString = testString;
226                     testString = "";
227                 }
228                 else
229                 {
230                     String JavaDoc row = "";
231                     for(int j=offset; j < i; j++)
232                         row = row + (String JavaDoc)v.get(j) + " ";
233                         
234                     lines.add(row);
235                     realString = "";
236                     testString = "";
237                     offset = i;
238                     realString = (String JavaDoc)v.get(i) + " ";
239                 }
240             }
241             else
242             {
243                 realString = testString;
244                 testString = "";
245             }
246         }
247
248         if(!realString.equalsIgnoreCase(""))
249             lines.add(realString);
250         
251             
252         Iterator JavaDoc i = lines.iterator();
253         while (i.hasNext())
254         {
255             String JavaDoc word = (String JavaDoc)i.next();
256             if(word != null && word.length() > 0)
257             {
258                 TextLayout JavaDoc layout = new TextLayout JavaDoc(word, font, g2d.getFontRenderContext());
259                 
260                 int centerX = this.textWidth / 2;
261                 int centeredTextStartX = centerX - ((int)layout.getVisibleAdvance() / 2);
262                 int rightTextStartX = this.textWidth - (int)layout.getVisibleAdvance();
263                 
264                 // Move y-coordinate by the ascent of the layout.
265
drawPosY += layout.getAscent();
266                     
267                 float drawPosX;
268                 if (layout.isLeftToRight())
269                 {
270                     if(this.alignment == ALIGN_CENTER)
271                         drawPosX = centeredTextStartX;
272                     if(this.alignment == ALIGN_RIGHT)
273                         drawPosX = rightTextStartX - textStartPosX;
274                     else
275                         drawPosX = textStartPosX;
276                 }
277                 else
278                 {
279                     drawPosX = textWidth - layout.getAdvance();
280                 }
281                         
282                 // Draw the TextLayout at (drawPosX, drawPosY).
283
layout.draw(g2d, drawPosX, drawPosY);
284                        
285                 // Move y-coordinate in preparation for next layout.
286
drawPosY += layout.getDescent() + layout.getLeading();
287             }
288         }
289
290     }
291
292
293     public void setCanvasHeight(int canvasHeight)
294     {
295         this.canvasHeight = canvasHeight;
296     }
297
298     public void setCanvasWidth(int canvasWidth)
299     {
300         this.canvasWidth = canvasWidth;
301     }
302
303     public void setTextHeight(int textHeight)
304     {
305         this.textHeight = textHeight;
306     }
307
308     public void setTextStartPosX(int textStartPosX)
309     {
310         this.textStartPosX = textStartPosX;
311     }
312
313     public void setTextStartPosY(int textStartPosY)
314     {
315         this.textStartPosY = textStartPosY;
316     }
317
318     public void setTextWidth(int textWidth)
319     {
320         this.textWidth = textWidth;
321     }
322
323     public void setBackgroundColor(Color JavaDoc backgroundColor)
324     {
325         this.backgroundColor = backgroundColor;
326     }
327
328     public void setForeGroundColor(Color JavaDoc foreGroundColor)
329     {
330         this.foreGroundColor = foreGroundColor;
331     }
332
333     public void setFontName(String JavaDoc fontName)
334     {
335         this.fontName = fontName;
336     }
337
338     public void setFontSize(int fontSize)
339     {
340         this.fontSize = fontSize;
341     }
342
343     public void setFontStyle(int fontStyle)
344     {
345         this.fontStyle = fontStyle;
346     }
347
348     public void setBackgroundImageUrl(String JavaDoc backgroundImageUrl)
349     {
350         this.backgroundImageUrl = backgroundImageUrl;
351     }
352
353     public int getAlignment()
354     {
355         return alignment;
356     }
357
358     public void setAlignment(int alignment)
359     {
360         this.alignment = alignment;
361     }
362
363 }
364
365
366
367
368
Popular Tags