01: /*
02: * This program is free software; you can redistribute it and/or modify
03: * it under the terms of the GNU General Public License as published by
04: * the Free Software Foundation; either version 2 of the License, or
05: * (at your option) any later version.
06: *
07: * This program is distributed in the hope that it will be useful,
08: * but WITHOUT ANY WARRANTY; without even the implied warranty of
09: * 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;
21: import java.io.IOException;
22: import java.io.OutputStream;
23:
24: import javax.imageio.ImageIO;
25:
26: import org.apache.commons.lang.RandomStringUtils;
27:
28: /**
29: * 随即图片生成器
30: * 该类用于用户注册时候需要用户根据图片内容进行填写正确后方可注册
31: * @author Liudong
32: */
33: public class RandomImageGenerator {
34:
35: public static String random() {
36: return RandomStringUtils.randomNumeric(4);
37: }
38:
39: /**
40: * 根据要求的数字生成图片,背景为白色,字体大小16,字体颜色黑色粗体
41: * @param num 要生成的数字
42: * @param out 输出流
43: * @throws IOException
44: */
45: public static void render(String num, OutputStream out)
46: throws IOException {
47: if (num.getBytes().length > 4)
48: throw new IllegalArgumentException(
49: "The length of param num cannot exceed 4.");
50: int width = 40;
51: int height = 15;
52: BufferedImage bi = new BufferedImage(width, height,
53: BufferedImage.TYPE_INT_RGB);
54: Graphics2D g = (Graphics2D) bi.getGraphics();
55: g.setColor(Color.WHITE);
56: g.fillRect(0, 0, width, height);
57: Font mFont = new Font("Tahoma", Font.PLAIN, 14);
58: g.setFont(mFont);
59: g.setColor(Color.BLACK);
60: g.drawString(num, 2, 13);
61: ImageIO.write(bi, "jpg", out);
62: }
63:
64: public static void main(String[] args) throws IOException {
65: String num = random();
66: System.out.println(num);
67: render(num, new FileOutputStream("D:\\test.jpg"));
68: System.out.println("Image generated.");
69: }
70: }
|