zoukankan      html  css  js  c++  java
  • struts2实现图片验证码

    生成图片验证码的主要工具类方法为:

      1 package com.yeting.fc.util;
      2 
      3 import java.awt.Color;
      4 import java.awt.Font;
      5 import java.awt.Graphics;
      6 import java.awt.image.BufferedImage;
      7 import java.io.ByteArrayInputStream;
      8 import java.io.ByteArrayOutputStream;
      9 import java.util.Random;
     10 
     11 import javax.imageio.ImageIO;
     12 import javax.imageio.stream.ImageOutputStream;
     13 
     14 public class ImageCodeUtil {
     15     /**
     16      * 生成随机验证码字符串
     17      * 
     18      * @return
     19      */
     20     public static String getImageCodeStr() {
     21 
     22         Random random = new Random();
     23         String code[] = { "A", "a", "B", "b", "C", "c", "D", "d", "E", "e",
     24                 "F", "f", "G", "g", "H", "h", "I", "i", "J", "j", "K", "k",
     25                 "L", "l", "M", "m", "N", "n", "O", "o", "P", "p", "Q", "q",
     26                 "R", "r", "S", "s", "T", "t", "U", "u", "V", "v", "W", "w",
     27                 "X", "x", "Y", "y", "Z", "z", "0", "1", "2", "3", "4", "5",
     28                 "6", "7", "8", "9", "0", "1", "2", "3", "4", "5", "6", "7",
     29                 "8", "9", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
     30                 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1",
     31                 "2", "3", "4", "5", "6", "7", "8", "9", "0", "1" };
     32         // 取随机产生的认证码(4位字符)
     33         StringBuffer codeStr = new StringBuffer("");
     34         for (int i = 0; i < 4; i++) {
     35             String cStr = code[random.nextInt(104)];
     36             codeStr.append(cStr);
     37         }
     38         return codeStr.toString();
     39     }
     40 
     41     /**
     42      * 生成带随机验证码的图片
     43      * 
     44      * @param codeStr
     45      * @return
     46      */
     47     public static BufferedImage createImage(String codeStr) {
     48         int width = 60, height = 20;
     49         BufferedImage image = new BufferedImage(width, height,
     50                 BufferedImage.TYPE_INT_RGB);
     51         // 获取图形上下文
     52         Graphics g = image.getGraphics();
     53         // 生成随机类
     54         Random random = new Random();
     55         // 设定背景色
     56         g.setColor(getRandColor(200, 250));
     57         g.fillRect(0, 0, width, height);
     58         // 设定字体
     59         g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
     60         // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
     61         g.setColor(getRandColor(160, 200));
     62         for (int i = 0; i < 155; i++) {
     63             int x = random.nextInt(width);
     64             int y = random.nextInt(height);
     65             int xl = random.nextInt(12);
     66             int yl = random.nextInt(12);
     67             g.drawLine(x, y, x + xl, y + yl);
     68         }
     69         for (int i = 0; i < codeStr.length(); i++) {
     70             String cStr = codeStr.charAt(i) + "";
     71             g.setColor(new Color(random.nextInt(125), random.nextInt(125),
     72                     random.nextInt(125)));
     73             g.setFont(new Font("", Font.PLAIN, 20 + random.nextInt(5)));
     74             g.drawString(cStr, 15 * i + random.nextInt(5),
     75                     20 - random.nextInt(5));
     76         }
     77         g.dispose();
     78         return image;
     79     }
     80 
     81     /**
     82      * 返回验证码图片的流格式
     83      * 
     84      * @param codeStr
     85      * @return
     86      */
     87     public static ByteArrayInputStream getImageAsInputStream(String codeStr) {
     88         BufferedImage image = createImage(codeStr);
     89         return convertImageToStream(image);
     90     }
     91     
     92     private static ByteArrayInputStream convertImageToStream(BufferedImage image) {
     93         ByteArrayInputStream inputStream = null;
     94         ByteArrayOutputStream output = null;
     95         ImageOutputStream imageOut = null;
     96         try {
     97             output = new ByteArrayOutputStream();
     98             imageOut = ImageIO.createImageOutputStream(output);
     99             ImageIO.write(image, "JPEG", imageOut);
    100             inputStream = new ByteArrayInputStream(output.toByteArray());
    101         } catch (Exception e) {
    102             e.printStackTrace();
    103         } finally{
    104             try {
    105                 if(imageOut!=null){
    106                     imageOut.close();
    107                 }
    108             } catch (Exception e2) {
    109                 e2.printStackTrace();
    110             }
    111         }
    112         return inputStream;
    113     }
    114 
    115     /*
    116      * 给定范围获得随机颜色
    117      */
    118     private static Color getRandColor(int fc, int bc) {
    119         Random random = new Random();
    120         if (fc > 255)
    121             fc = 255;
    122         if (bc > 255)
    123             bc = 255;
    124         int r = fc + random.nextInt(bc - fc);
    125         int g = fc + random.nextInt(bc - fc);
    126         int b = fc + random.nextInt(bc - fc);
    127         return new Color(r, g, b);
    128     }
    129 
    130 }

    Action中主要代码为:

    package com.yeting.fc.action;
    
    import java.io.ByteArrayInputStream;
    
    import com.opensymphony.xwork2.ActionContext;
    import com.opensymphony.xwork2.ActionSupport;
    import com.yeting.fc.util.ImageCodeUtil;
    
    public class ImageCodeAction extends ActionSupport{
        private static final long serialVersionUID = 1L;
        private ByteArrayInputStream inputStream;  
        public String getImageCode() throws Exception{
            //获取图片字符串
            String codeStr = ImageCodeUtil.getImageCodeStr();
            ActionContext.getContext().getSession().put("rand",codeStr);
            //System.out.println(codeStr);
            inputStream = ImageCodeUtil.getImageAsInputStream(codeStr);
            return SUCCESS;  
        }  
        
        public void setInputStream(ByteArrayInputStream inputStream) {  
            this.inputStream = inputStream;  
        }  
        public ByteArrayInputStream getInputStream() {  
            return inputStream;  
        }  
      
    }

    struts.xml文件中配置如下:

    1 <!-- 验证码Action -->
    2    <action name="imageCode" class="imageCodeAction" method="getImageCode">
    3         <result type="stream">  
    4             <param name="contentType">image/jpeg</param>  
    5             <param name="inputName">inputStream</param>  
    6         </result> 
    7    </action>

    登陆页面:主要代码。

     1 <!--刷新请求,更换验证码内容。-->
     2 <script type="text/javascript">
     3     function imageCode(){
     4         document.getElementById("imageCode").src="${pageContext.request.contextPath }/yeting/imageCode.action?st="+new Date();
     5     }
     6 </script>
     7 
     8 
     9 
    10 <!--验证码主要html文件-->
    11 
    12     验证码:<input style="50px;" type="text" name="imageCode"/>
    13           <a href="javascript:imageCode()">
    14                 <img style="margin-top: 5px;" id="imageCode" src="${pageContext.request.contextPath }/yeting/imageCode.action"/>
    15           </a>
    16           <a href="javascript:imageCode()"><input style="35px;" type="button" value="更换"/></a>
    17 
  • 相关阅读:
    Django之数据库表的创建和ORM相关操作
    Django后续和Ajax初识
    阿里云Maven中央仓库配置
    java/javascript 时间操作工具类
    原生javascript实现文件异步上传
    MySQL中的存储函数和存储过程的简单示例
    java同步锁的正确使用
    浅谈javascript的面向对象思想
    java与javascript对cookie操作的工具类
    json字符串与json对象的相互转换
  • 原文地址:https://www.cnblogs.com/yemaozistar/p/3605181.html
Copyright © 2011-2022 走看看