KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > dlog4j > util > image > RandomImageGenerator


1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 2 of the License, or
5  * (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU Library General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15  */

16 package dlog4j.util.image;
17
18 import java.awt.*;
19 import java.awt.image.*;
20 import java.io.FileOutputStream JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.io.OutputStream JavaDoc;
23
24 import javax.imageio.ImageIO JavaDoc;
25
26 import org.apache.commons.lang.RandomStringUtils;
27 /**
28  * 随即图片生成器
29  * 该类用于用户注册时候需要用户根据图片内容进行填写正确后方可注册
30  * @author Liudong
31  */

32 public class RandomImageGenerator {
33     
34     public static String JavaDoc random() {
35         return RandomStringUtils.randomNumeric(4);
36     }
37     /**
38      * 根据要求的数字生成图片,背景为白色,字体大小16,字体颜色黑色粗体
39      * @param num 要生成的数字
40      * @param out 输出流
41      * @throws IOException
42      */

43     public static void render(String JavaDoc num, OutputStream JavaDoc out) throws IOException JavaDoc{
44         if(num.getBytes().length>4)
45             throw new IllegalArgumentException JavaDoc("The length of param num cannot exceed 4.");
46         int width = 40;
47         int height = 15;
48         BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
49         Graphics2D g = (Graphics2D)bi.getGraphics();
50         g.setColor(Color.WHITE);
51         g.fillRect(0,0,width,height);
52         Font mFont = new Font("Tahoma", Font.PLAIN, 14);
53         g.setFont(mFont);
54         g.setColor(Color.BLACK);
55         g.drawString(num,2,13);
56         ImageIO.write(bi,"jpg",out);
57     }
58     
59     public static void main(String JavaDoc[] args) throws IOException JavaDoc{
60         String JavaDoc num = random();
61         System.out.println(num);
62         render(num,new FileOutputStream JavaDoc("D:\\test.jpg"));
63         System.out.println("Image generated.");
64     }
65 }
66
Popular Tags