java 生成验证码图片

图片对象

  1 import java.awt.Color;
  2 import java.awt.Font;
  3 import java.awt.Graphics;
  4 import java.awt.image.BufferedImage;
  5 import java.io.ByteArrayInputStream;
  6 import java.io.ByteArrayOutputStream;
  7 import java.io.IOException;
  8 import java.util.Random;
  9 import javax.imageio.ImageIO;
 10 import javax.imageio.stream.ImageOutputStream;
 11 import javax.servlet.ServletException;
 12 import javax.servlet.http.HttpServlet;
 13 import javax.servlet.http.HttpServletRequest;
 14 import javax.servlet.http.HttpServletResponse;
 15 
 16 
 17 public class VImage extends HttpServlet {
 18     /**
 19      * serialVersionUID
 20      */
 21     private static final long serialVersionUID = 1L;
 22     
 23     private ByteArrayInputStream image;
 24 
 25     public ByteArrayInputStream getImage() {
 26         return image;
 27     }
 28 
 29     public void setImage(ByteArrayInputStream image) {
 30         this.image = image;
 31     }
 32 
 33     Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
 34         Random random = new Random();
 35         if (fc > 255)
 36             fc = 255;
 37         if (bc > 255)
 38             bc = 255;
 39         int r = fc + random.nextInt(bc - fc);
 40         int g = fc + random.nextInt(bc - fc);
 41         int b = fc + random.nextInt(bc - fc);
 42         return new Color(r, g, b);
 43     }
 44 
 45     public void doGet(HttpServletRequest request, HttpServletResponse response)
 46             throws ServletException, IOException {
 47 
 48         // 设置页面不缓存
 49 
 50         response.setHeader("Pragma", "No-cache");
 51         response.setHeader("Cache-Control", "no-cache");
 52         response.setDateHeader("Expires", 0);
 53 
 54         // 在内存中创建图象
 55         int width = 100, height = 30;
 56         BufferedImage image = new BufferedImage(width, height,
 57                 BufferedImage.TYPE_INT_RGB);
 58 
 59         // 获取图形上下文
 60 
 61         Graphics g = image.getGraphics();
 62 
 63         // 生成随机类
 64 
 65         Random random = new Random();
 66 
 67         // 设定背景色
 68 
 69         g.setColor(getRandColor(200, 250));
 70         g.fillRect(0, 0, width, height);
 71 
 72         // 设定字体
 73         g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
 74 
 75         // 画边框
 76 
 77         // g.setColor(new Color());
 78         // g.drawRect(0,0,width-1,height-1);
 79 
 80         // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
 81 
 82         g.setColor(getRandColor(160, 200));
 83         for (int i = 0; i < 155; i++) {
 84             int x = random.nextInt(width);
 85             int y = random.nextInt(height);
 86             int xl = random.nextInt(12);
 87             int yl = random.nextInt(12);
 88             g.drawLine(x, y, x + xl, y + yl);
 89         }
 90 
 91         // 取随机产生的认证码(4位数字)
 92         String sRand = "";
 93         for (int i = 0; i < 4; i++) {
 94             String rand = String.valueOf(random.nextInt(10));
 95             sRand += rand;
 96             // 将认证码显示到图象中
 97             g.setColor(new Color(20 + random.nextInt(110), 20 + random
 98                     .nextInt(110), 20 + random.nextInt(110)));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
 99 
100             g.drawString(rand, 25 * i + 6, 22);    //验证码在图片中的显示位置
101         }
102 
103         //将认证码存入SESSION
104         request.getSession().setAttribute("rand", sRand);
105 
106         // 图象生效
107         g.dispose();
108         
109         ByteArrayInputStream input = null;
110         ByteArrayOutputStream output = new ByteArrayOutputStream();
111         try {
112             ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
113             // 输出图象到页面
114 
115             ImageIO.write(image, "JPEG", imageOut);
116             imageOut.close();
117             input = new ByteArrayInputStream(output.toByteArray());
118         } catch (Exception e) {
119             //not handle
120         }
121 
122         this.image = input;
123     }
124 }

相关action

 1 import java.io.ByteArrayInputStream;
 2 import java.io.IOException;
 3 import javax.servlet.ServletException;
 4 import org.apache.log4j.Logger;
 5 import org.apache.struts2.ServletActionContext;
 6 
 7 import com.keertech.base.action.AbstractAction;
 8 import com.keertech.util.VImage;
 9 
10 
11 public class ImageAction extends AbstractAction {
12     /**
13      * serialVersionUID
14      */
15     private static final long serialVersionUID = 1L;
16     
17     /**
18      * log
19      */
20     private Logger log = Logger.getLogger(this.getClass().getName());
21     
22     private ByteArrayInputStream inputStream;  
23 
24     public String getValCode(){
25         VImage v=new VImage();
26         try {
27             v.doGet(ServletActionContext.getRequest(), ServletActionContext.getResponse());
28             this.setInputStream(v.getImage());
29         } catch (ServletException e) {
30             log.info(e.getMessage());
31         } catch (IOException e) {
32             log.info(e.getMessage());
33         }
34         
35         return SUCCESS;
36     }
37     
38     public ByteArrayInputStream getInputStream() {
39         return inputStream;
40     }
41     
42     public void setInputStream(ByteArrayInputStream inputStream) {
43         this.inputStream = inputStream;
44     }
45 }

struts配置

1 <action name="rand" class="com.keertech.web.action.ImageAction"
2             method="getValCode">
3             <result type="stream">
4                 <param name="contentType">image/jpeg</param>
5                 <param name="inputName">inputStream</param>
6             </result>
7         </action>

js

1 function changeValidateCode(obj) {
2             var myDate = new Date();
3             obj.src = "webbase/rand.action?date=" + myDate;
4         }

html

1 <img style="display: block;float: left;cursor:hand;" src="rand.action" id="valImg" onclick="changeValidateCode(this)" title="更换验证码" />

 

posted on 2014-11-04 11:22  看天空的星星  阅读(190)  评论(0编辑  收藏  举报

导航