java生成图片验证码

java

浏览数:188

2019-1-8

片段 1片段 2


需用ajax到后台请求

@Controller
public class RandomPictureController extends ControllerUtil {

    /*
     * 随机字符字典
     */
    private static final char[] CHARS = { '2', '3', '4', '5', '6', '7', '8',
            '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
            'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

    /*
     * 随机数
     */
    private static Random random = new Random();

    /*
     * 获取6位随机数
     */
    private static String getRandomString() {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            buffer.append(CHARS[random.nextInt(CHARS.length)]);
        }
        return buffer.toString();
    }

    /*
     * 获取随机数颜色
     */
    private static Color getRandomColor() {
        return new Color(random.nextInt(255), random.nextInt(255), random
                .nextInt(255));
    }

    /*
     * 返回某颜色的反色
     */
    private static Color getReverseColor(Color c) {
        return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c
                .getBlue());
    }

    /**
     * 生成验证码
     * 
     * @return String
     */
    @RequestMapping("/rand_getCode.html")
    public void getCode(HttpServletRequest request, HttpServletResponse response) {
        try {
            int width = 63;
            int height = 37;
            Random random = new Random();
            //设置response头信息
            //禁止缓存
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);

            //生成缓冲区image类
            BufferedImage image = new BufferedImage(width, height, 1);
            //产生image类的Graphics用于绘制操作
            Graphics g = image.getGraphics();
            //Graphics类的样式
            g.setColor(this.getRandColor(200, 250));
            g.setFont(new Font("Times New Roman",0,28));
            g.fillRect(0, 0, width, height);
            //绘制干扰线
            for(int i=0;i<40;i++){
                g.setColor(this.getRandColor(130, 200));
                int x = random.nextInt(width);
                int y = random.nextInt(height);
                int x1 = random.nextInt(12);
                int y1 = random.nextInt(12);
                g.drawLine(x, y, x + x1, y + y1);
            }

            //绘制字符
            String strCode = "";
            for(int i=0;i<4;i++){
                String rand = String.valueOf(random.nextInt(10));
                strCode = strCode + rand;
                g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
                g.drawString(rand, 13*i+6, 28);
            }
            //将字符保存到session中用于前端的验证
            request.getSession().setAttribute("strCode",strCode);
            g.dispose();

            ImageIO.write(image, "JPEG", response.getOutputStream());
            response.getOutputStream().flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    Color getRandColor(int fc,int bc){
        Random random = new Random();
        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);
    }
}

/**
     * 验证码验证
     * @param req
     * @param resp
     * @throws Exception
     */
    @RequestMapping("/rand_vaildata.html")
    public void vailDataCode(HttpServletRequest req,HttpServletResponse resp) throws Exception {
        Map<String,String> mapStr=UtilJson.toMap(req.getParameter("mapStr"));
        String code = (String)req.getSession().getAttribute("strCode");//拿到缓存中的验证码
        Map<String, Object> mapInfo=new HashMap<String, Object>();
        if(code.equals(mapStr.get("code"))){
            mapInfo.put("code",SysFinal.SUCCESS);
            mapInfo.put("info", "");
        }else {
            mapInfo.put("code",SysFinal.FAIL);
            mapInfo.put("info", "验证码有误");
        }
        this.respBack(UtilJson.mapToJson(mapInfo), resp);
    }


前台

/**
 * 刷新验证码
 * @param imgCode img对象ID
 */
function chageCode(){
    $('#imgCode').attr('src','rand_getCode.html?abc='+Math.random());//链接后添加Math.random,确保每次产生新的验证码,避免缓存问题。
}/**
*当失去焦点时就开始进行验证
*
*/
$("#vaidataCodeInfo").blur(function(){
        var code=$("#vaidataCodeInfo").val();
        if(code==""){
            $("#verificationInfo").html("请填写验证码");
        }
        var jsonObj={
                "code":code
        }
        var jsonAjax={
                "url":"rand_vaildata.html",
                "jsonData":{"mapStr":jsonToStr(jsonObj)},
                "methodName":"rand_vaildata"
        }
        getAjaxData(jsonAjax);
    });
});

/**
 * 验证回调
 * @param jsonObj
 * @return
 */
function rand_vaildata(jsonObj){
    var data = strToJson(jsonObj.data);
    if (data.code=="fail") {
        $("#verificationInfo").html(data.info);
    }else{
        $("#verificationInfo").html(data.info);
    }
}