网页验证码的绘制模板(Java)

@WebServlet(name = "Demo10Servlet", urlPatterns = "/vcode")
public class Demo10Servlet extends HttpServlet {
    
    //创建随机对象
    private Random ran = new Random();

    // 写一个方法随机获取颜色
    public Color getRanColor() {
        int r = ran.nextInt(256);
        int b = ran.nextInt(256);
        int g = ran.nextInt(256);

        return new Color(r, b, g);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 创建缓存图片:指定宽width=90,高height=30
        int width = 90;
        int height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取画笔对象
        Graphics graphics = image.getGraphics();
        // 设置画笔颜色,并且填充矩形区域
        graphics.setColor(Color.white);//设置背景为白色
        //并且设置填充矩形区域
        graphics.fillRect(0, 0, width, height);
        // 从字符数组中随机得到字符
        char[] arr = {'A', 'B', 'C', 'D', 'J', 'U', 'N', 'G', 'A', 'N', '1', '2', '3', '4'};
        //设置循环,得到四个数
        for (int i = 0; i < 4; i++) {
            //得到索引
            int index = ran.nextInt(arr.length);
            //取出一个字符
            char c = arr[index];
            // 设置字体,大小为18,设置字的颜色随机
            graphics.setFont(new Font(Font.DIALOG, Font.BOLD + Font.ITALIC, 19));
            //设置背景颜色
            graphics.setColor(getRanColor());
            //把字符转成字符串
            // 将每个字符画到图片,位置:5+(i*20), 20
            graphics.drawString(String.valueOf(c), 10 + (i * 20), 20);
        }
        // 画干扰线8条线,线的位置是随机的,x范围在width之中,y的范围在height之中。
        for (int i = 0; i < 8; i++) {
            graphics.setColor(getRanColor());
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);
            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            graphics.drawLine(x1, y1, x2, y2);

        }
        // 将缓存的图片输出到响应输出流中
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值