验证码

新代码

/**
 * 获取验证码和图片
 * 
 * @return list包含两个对象,第一个是验证码对应字符串(String),第二个是验证码图片(BufferedImage)
 */
public static ArrayList<Object> getSecurityCode() {
    // 验证码图片对应的字符串
    StringBuilder sb = new StringBuilder();
    // 验证码图片宽高
    int width = 120;
    int height = 40;
    // 可能出现的字符
    char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
    // 随机数
    Random ran = new Random();
    // 创建空白画布
    BufferedImage bufImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    // 获得画笔
    Graphics2D g = (Graphics2D) bufImage.getGraphics();
    // 填充背景为随机颜色
    g.setColor(new Color(ran.nextInt(50), ran.nextInt(50), ran.nextInt(50)));
    g.fillRect(0, 0, width, height);
    // 填充字体
    g.setFont(new Font("font", Font.BOLD, 30));// 设置字体
    for (int i = 1; i <= 4; i++) {
        // 随机颜色,随机字符
        g.setColor(new Color(ran.nextInt(55) + 200, ran.nextInt(55) + 200, ran.nextInt(55) + 200));
        char ch = chars[(int) (Math.random() * chars.length)];
        sb.append(ch);
        // 设置字体倾斜
        int jiaodu = (int) (Math.random() * 60) - 30;// 旋转 -30 ~ 30度
        double theta = jiaodu * Math.PI / 180;// 换算弧度
        g.rotate(theta, width / 5 * i, height - 10);
        g.drawString(ch + "", width / 5 * i - 8, height - 10);// 画字符
        g.rotate(-theta, width / 5 * i, height - 10);
    }
    // 绘制干扰线
    int x1, x2, y1, y2;
    for (int i = 0; i < 5; i++) {
        g.setColor(new Color(ran.nextInt(255), ran.nextInt(255), ran.nextInt(255)));
        x1 = (int) (Math.random() * width);
        x2 = (int) (Math.random() * width);
        y1 = (int) (Math.random() * height);
        y2 = (int) (Math.random() * height);
        g.drawLine(x1, y1, x2, y2);
    }
    g.dispose();// 释放画笔资源
    // 返回验证码和图片
    ArrayList<Object> list = new ArrayList<>();
    list.add(sb.toString());
    list.add(bufImage);
    return list;
}

servlet配置

// 设置不缓存图片  
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
// 设置响应图片类型
response.setContentType("image/jpeg");
// 输出图片
ImageIO.write(image,"JPEG",response.getOutputStream());

生成验证码示例

以上代码所生成的验证码

修改

  • 修改了背景和字体颜色取值范围,背景深色,字体浅色,解决验证码字体可能看不清的问题
  • 字体整体向左移动8个单位以居中

修改后生成的验证码

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值