看代码和注释
用于产生验证码
1 package com.whbweb.top.util;
2
3 import java.awt.Color;
4 import java.awt.Font;
5 import java.awt.Graphics2D;
6 import java.awt.image.BufferedImage;
7 import java.util.Random;
8
9 public class Identity {
10 //随机字符的范围
11 private final char[] CHARS={'2','3','4','5','6','7','8','9','A','B','C','D','E','F','J'
12 ,'H','G','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z'};
13 //随机数的对象
14 private Random random=new Random();
15 //产生的随机数
16 private String identityString;
17 //得到随机数字符串
18 private String identityString(){
19 StringBuffer identityBuffer=new StringBuffer();
20 for(int i=0;i<6;i++){//产生6个随机数
21 identityBuffer.append(CHARS[random.nextInt(CHARS.length)]);
22 }
23 System.out.println(identityBuffer);
24 identityString=identityBuffer.toString();
25 return identityBuffer.toString();
26 }
27 //产生随机前景色
28 private Color getRandomColor(){
29 return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
30 }
31 //通过前景色得到背景色
32 private Color getReverseColor(Color c){
33 return new Color(255-c.getRed(),255-c.getGreen(),255-c.getBlue());
34 }
35 //获取随机数图片,输入图片的宽度和高度以及字体的大小
36 public BufferedImage getIdentityBit(int width,int height,int fontSize){
37 //创建一个RGB类型的图片
38 BufferedImage bi=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
39 //获取随机颜色
40 Color color=getRandomColor();
41 //获取背景色
42 Color backColor=getReverseColor(color);
43 //获取验证码
44 String text=identityString();
45 //创建2D绘图工具,通过bi来创建
46 Graphics2D gp2d=bi.createGraphics();
47 //设置字体属性参数二为加粗,参数三为字体大小
48 gp2d.setFont(new Font(Font.SANS_SERIF, Font.BOLD, fontSize));
49 //设置前景色
50 gp2d.setColor(color);
51 //填充背景
52 gp2d.fillRect(0, 0, width, height);
53 //设置背景色
54 gp2d.setColor(backColor);
55 //将text文本写入图片
56 gp2d.drawString(text,18,20);
57 //产生50-100个噪点
58 int n=random.nextInt(50)+50;
59 for(int i=0;i<n;i++){
60 //填充噪点,参数一二位起始坐标,参数三四位噪点大小
61 gp2d.drawRect(random.nextInt(width), random.nextInt(height),random.nextInt(2), random.nextInt(2));
62 }
63 return bi;
64 }
65 //获取验证码
66 public String getIdentityString(){
67 return identityString;
68 }
69 }
用于输出验证码图片,并将验证码放入session域中
1 @Override
2 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
3 resp.setContentType("image/jpeg");
4 OutputStream ops=resp.getOutputStream();
5 JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(ops);
6 Identity identity=new Identity();
7 encoder.encode(identity.getIdentityBit(100, 30, 16));
8 req.getSession().setAttribute("Identity", identity.getIdentityString());
9 ops.flush();
10 ops.close();
11
12 }
页面调用时,将img的src设置为servlet路径即可
转载请注明出处http://blog.csdn.net/whb3299065/article/details/53330617