java生成验证码图片

public class AuthImg extends HttpServlet {

    /**
     *
     */
    private static final long serialVersionUID = 4975974534946437434L;

    // 设置图形验证码字符串的字体和大小
    private Font mFont = new Font("微软雅黑", Font.ITALIC, 18);

    private Random random = new Random();

    public void init() throws ServletException {
        super.init();
    }

    // 生成服务器响应的Service方法
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 阻止生成的页面被缓存,保证每次都生成新的验证码
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 指定验证码图片的大小
        int width = 80, height = 24;
        // 生成一张新的图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        // 在图片中绘制内容
        Graphics g = image.getGraphics();
        g.setColor(new Color(252, 252, 252));
        g.fillRect(1, 1, width, height);
        g.setColor(new Color(252, 252, 252));
        g.drawRect(0, 0, width, height);
        g.setFont(mFont);
        g.setColor(new Color(252, 252, 252));

        // 该变量用于保存系统生成的随机变量字符串
        String sRand = "";
        int colorR = random.nextInt(200);
        int colorG = random.nextInt(200);
        int colorB = random.nextInt(200);
        for (int i = 0; i < 4; i++) {
            // 取得一个随机字符串
            String tmp = getRandomChar();
            sRand += tmp;
            // 将系统生成的随机字符串添加到图片上
            g.setColor(new Color(colorR, colorG, colorB));
            g.drawString(tmp, 15 * i + 10, 20);
        }
        // 取得用户的Session
        HttpSession session = request.getSession(true);
        // 将系统生成的随机验证码添加到用户Session中
        session.setAttribute("rand", sRand);
        g.dispose();
        // 输出验证码图片
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }

    // 生成随机字符串的方法
    private String getRandomChar() {
        int itmp = random.nextInt(10);
        return String.valueOf(itmp);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wuyongde0922

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值