写一个自己的验证码工具类

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 *@author frunqer 
 *@time 2016年5月13日 下午9:31:47 
 *@note 这是生成验证码的帮助类
 */
public class ValidateCode {
    private static String validateCode=""; //定义静态变量用来存放生成的验证码
    /**
     * @author frunqer
     * @time 2016年5月13日 下午9:28:00
     * @tags @param width 矩形验证码宽
     * @tags @param height 验证码高
     * @tags @param size  验证码字体大小
     * @tags 这是获得验证码图片的方法
     */
    public static BufferedImage getImage(int width,int height,int size){
        //创建一个缓冲图片
        BufferedImage image=new BufferedImage(90, 40, BufferedImage.TYPE_INT_BGR);
        //创建一个随机数
        Random random=new Random();
        //创建一个画笔
        Graphics g=image.getGraphics();
        //画一个矩形
        g.fillRect(0, 0, width, height);
        //定义一个可选字符范围
        char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
        int length=ch.length;
        //定义一个随机颜色
        Color color=new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
        //定义5中随机字体
        Font[] fonts=new Font[5];
        fonts[0]=new Font("Ravie", Font.PLAIN, size);
        fonts[1]=new Font("Autique olive compact", Font.PLAIN, size);
        fonts[2]=new Font("Forte",Font.PLAIN,size);
        fonts[3]=new Font("Wide Latin", Font.PLAIN,size);
        fonts[4]=new Font("Gill Sans Ultra Bold", Font.PLAIN, size);
        Font font=fonts[random.nextInt(5)];
        //生成4位字符验证码
        for(int i=0;i<4;i++){
            if(i==0){
              setValidateCode(""); //每次重新生成验证码前 要将validateCode值清空
            }
            g.setFont(font);//设置字体样式
            String code=new Character(ch[random.nextInt(length)]).toString();//设置单个随机字符
            ValidateCode.setValidateCode(getValidateCode() + code);
            g.setColor(color);
            g.drawString(code, 20*i+6, 25);
        }
        //生成干扰线
        for(int i=0;i<100;i++){
            int x=random.nextInt(width);
            int y=random.nextInt(height);
            g.drawOval(x, y, 2, 2);

        }
        g.dispose();
        return image;

    }

    //这是获得验证码内容的方法
    public static String getValidateCode() {
        return validateCode;
    }
    public static void setValidateCode(String validateCode) {
        ValidateCode.validateCode = validateCode;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值