验证码生成

根据传入的count值,生成count位的验证码

/*
 * 验证码生成器
 */
@Controller
@RequestMapping("/tools/identiry")
public class IdentifyCodeController {
    @RequestMapping("/code")
    public void init(HttpServletRequest request, HttpServletResponse response){
        //生成随机字符串,保存在SessionContext中,还可以保存在redis中
        String random=RandomStringUtils.randomAlphanumeric(4); 
        SessionContext.setAttribute(request, SessionContext.IDENTIFY_CODE_KEY, random);
        response.setContentType("image/jpeg"); 
        response.addHeader("pragma", "NO-cache"); 
        response.addHeader("Cache-Control","no-cache");
        //浏览器不响应缓存
        response.addDateHeader("Expries",0);

        //将随机字符串显示在图像中,前端直接显示这里生成的带随机字符串的图像
        int width=110, height=33;
        //创建一个全新的BufferImage图像对象
        //width表示图像的宽度,height表示图像的高度,最后一个参数表示图像字节灰度图像
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //创建Graphics对象,用来获取画笔
        Graphics g = image.getGraphics();
        //以下填充背景色 
        g.setColor(new Color(225,225,225)); 
        Font DeFont=new Font("SansSerif", Font.PLAIN, 26);   
        g.setFont(DeFont); 
        g.fillRect(0, 0, width, height); 
        //设置字体色 
        g.setColor(Color.BLACK);
        //图像中要绘制的文本
        g.drawString(random,20,25);
        //graphics释放资源
        g.dispose(); 
        try {
            ServletOutputStream outStream = response.getOutputStream();
            //将JPG格式的BufferImage图像对象写入输出流
            ImageIO.write(image, "JPG", outStream);
            outStream.close(); 
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }
}

可直接生成random随机数,传入count值为4,start=0,end=0,letters=true,number=true,chars=null,random=new Random()

public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random) {

    if (count == 0) {
        return "";
    } else if (count < 0) {
        throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
    } else {
        if (start == 0 && end == 0) {
            end = 123;
            start = 32;
            if (!letters && !numbers) {
                start = 0;
                end = 2147483647;
            }
        }
        char[] buffer = new char[count];
        int gap = end - start;
        while(true) {
            while(true) {
            //根据count生成随机数,传入的count为4,则生成4个随机数
                while(count-- != 0) {
                    char ch;
                    if (chars == null) {
                        ch = (char)(random.nextInt(gap) + start);
                    } else {
                        ch = chars[random.nextInt(gap) + start];
                    }
                     if (letters && Character.isLetter(ch) || numbers && Character.isDigit(ch) || !letters && !numbers) {
                        if (ch >= '\udc00' && ch <= '\udfff') {
                            if (count == 0) {
                                ++count;
                            } else {
                                buffer[count] = ch;
                                --count;
                                buffer[count] = (char)('\ud800' + random.nextInt(128));
                            }
                        } else if (ch >= '\ud800' && ch <= '\udb7f') {
                            if (count == 0) {
                                ++count;
                            } else {
                                buffer[count] = (char)('\udc00' + random.nextInt(128));
                                --count;
                                buffer[count] = ch;
                            }
                        } else if (ch >= '\udb80' && ch <= '\udbff') {
                            ++count;
                        } else {
                            buffer[count] = ch;
                        }
                    } else {
                        ++count;
                    }
                }
                return new String(buffer);
            }
        }
    }
}

方法二:

也可根据当前时间生成随机验证码,同样是传入count值

//使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符  
public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";  
private static Random random = new Random();  
    
/** 
 * 使用指定源生成验证码 
 * @param verifySize    验证码长度 
 * @param sources   验证码字符源 
 * @return 
 */  
public static String generateVerifyCode(int verifySize, String sources){  
    if(sources == null || sources.length() == 0){  
        sources = VERIFY_CODES;  
    }  
    int codesLen = sources.length();  
    Random rand = new Random(System.currentTimeMillis());  
    StringBuilder verifyCode = new StringBuilder(verifySize);  
    for(int i = 0; i < verifySize; i++){  
        verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));  
    }
    System.out.println("java底层生成图形验证码字符:" + verifyCode.toString());
    return verifyCode.toString();  
} 

直接显示验证码图像

    /** 
     * 输出指定验证码图片流 
     * @param w 
     * @param h 
     * @param os 
     * @param code 
     * @throws IOException 
     */  
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{  
        int verifySize = code.length();  
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);  
        Random rand = new Random();  
        Graphics2D g2 = image.createGraphics();  
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);  
        Color[] colors = new Color[5];  
        Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,  
                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,  
                Color.PINK, Color.YELLOW };  
        float[] fractions = new float[colors.length];  
        for(int i = 0; i < colors.length; i++){  
            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];  
            fractions[i] = rand.nextFloat();  
        }  
        Arrays.sort(fractions);  
          
        g2.setColor(Color.GRAY);// 设置边框色  
        g2.fillRect(0, 0, w, h);  
          
        Color c = getRandColor(200, 250);  
        g2.setColor(c);// 设置背景色  
        g2.fillRect(0, 2, w, h-4);  
          
        //绘制干扰线  
        Random random = new Random();  
        g2.setColor(getRandColor(160, 200));// 设置线条的颜色  
        for (int i = 0; i < 20; i++) {  
            int x = random.nextInt(w - 1);  
            int y = random.nextInt(h - 1);  
            int xl = random.nextInt(6) + 1;  
            int yl = random.nextInt(12) + 1;  
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);  
        }  
          
        // 添加噪点  
        float yawpRate = 0.05f;// 噪声率  
        int area = (int) (yawpRate * w * h);  
        for (int i = 0; i < area; i++) {  
            int x = random.nextInt(w);  
            int y = random.nextInt(h);  
            int rgb = getRandomIntColor();  
            image.setRGB(x, y, rgb);  
        }  
          
        shear(g2, w, h, c);// 使图片扭曲  
  
      //g2.setColor(getRandColor(100, 160));  
        g2.setColor(new Color(197,54,12));
        int fontSize = h-4;  
      //Font font = new Font("Algerian", Font.ITALIC, fontSize);  
        
        Font font = new Font("Cancun", Font.PLAIN, 22);
        
        g2.setFont(font);  
        char[] chars = code.toCharArray();  
        for(int i = 0; i < verifySize; i++){  
            AffineTransform affine = new AffineTransform();  
            affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);  
            g2.setTransform(affine);  
            g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);  
        }  
          
        g2.dispose();  
        ImageIO.write(image, "jpg", os);  
    }  
    private static Color getRandColor(int fc, int bc) {  
        if (fc > 255)  
            fc = 255;  
        if (bc > 255)  
            bc = 255;  
        int r = fc + random.nextInt(bc - fc);  
        int g = fc + random.nextInt(bc - fc);  
        int b = fc + random.nextInt(bc - fc);  
        return new Color(r, g, b);  
    }
  

前端页面直接调用后端接口,后端直接创建ImageIO对象,通过response.getOutputStream()输出流显示验证码:

<form id="registerForm" method="post" action="${s.base}/auth/doRegister.html" class="oc-form"  style="text-align: center;border: 1px solid #CCC;width: 600px;margin:0 auto;padding:20px;" >
    <li><label>用户名</label>
        <input maxlength="20" id="username" name="username"  type="text"  class="input-text"  placeholder="请输入用户名(英文数字)" >
    </li>
    <li><label>密码</label>
        <input maxlength="20" id="password" name="password" type="password" class="input-text" placeholder="请输入密码" autocomplete="off" />
    </li>
    <li><label>验证码</label>
        <input id="identiryCode" name="identiryCode" maxlength="6" class="input-text" type="text" style="width: 150px;" placeholder="请输入验证码"/>
        <a class="vali-base"><img  onclick="reloadIndityImg('indeityImgRegister');" id="indeityImgRegister"  src="${s.base}/tools/identiry/code.html" style="width:80px;height:40px;float:left;margin-left:10px;"/></a>
    </li>
    <li id="errorMsg" class="clearfix" style="display: none;color:red;">用户名密码不能为空</li>
    <li class="clearfix" style="margin-top: 30px;">
        <input type="button" value="注册保存" class="btn" onclick="doSubmit();">
    </li>
    <li>
        <a style="float: left;" href="${s.base}/auth/login.html">已有账号,去登录</a>
    </li>
</form>

posted on 2019-06-19 16:33  夜萤火虫和你  阅读(160)  评论(0编辑  收藏  举报

导航