zoukankan      html  css  js  c++  java
  • java Web 请求servlet绘制验证码简单例子

    主要用来了解java代码怎么绘制验证码图片,实际开发中不会这样用

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //生成画布
            int width = 120;
            int height = 40;
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //获取画笔
            Graphics g = bi.getGraphics();
            //填充背景色
            g.setColor(Color.white);//背景色
            g.fillRect(0, 0, width, height);//在画布的位置
            //绘制边框
            g.setColor(Color.green);//边框颜色
            g.drawRect(0, 0, width - 1, height - 1);//边框大小
            //生成4个随机字符 并放到code变量中
            String code = "";
            Random rd = new Random();
            String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
            for (int i = 0; i < 4; i++) {
                //设置字体
                g.setFont(new Font("微软雅黑", Font.BOLD, 30));
                //设置颜色
                g.setColor(new Color(rd.nextInt(255), rd.nextInt(255), rd.nextInt(255)));
                //绘制字符
                String str = data.charAt(rd.nextInt(data.length())) + "";
                g.drawString(str, 10 + i * 30, 30);
                code += str;
            }
            //绘制干扰线
            for (int i = 0; i < 5; i++) {
                //干扰线随机颜色
                g.setColor(new Color(rd.nextInt(255), rd.nextInt(255), rd.nextInt(255)));
                //绘制干扰线
                g.drawLine(rd.nextInt(width), rd.nextInt(height), rd.nextInt(width), rd.nextInt(height));
            }
            //输出到页面
            ImageIO.write(bi, "png", response.getOutputStream());
        }
  • 相关阅读:
    对比使用Charles和Fiddler两个工具及利用Charles抓取https数据(App)
    Charles-安装和配置
    python算法-队列
    python算法-快速排序
    【Codeforces】383.DIV2
    static关键字
    UNIX环境高级编程--5
    【LeetCode】467. Unique Substrings in Wraparound String
    typedef关键字
    strcpy 和 memcpy自实现
  • 原文地址:https://www.cnblogs.com/blazeZzz/p/9231094.html
Copyright © 2011-2022 走看看