【Java】【web】验证码

验证码

public class CodeImg extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int width = 110;
        int height = 25;
        // 在内存中创建一个图片
        BufferedImage img = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
    
        // 创建画笔
        Graphics g = img.getGraphics();
    
        // 添加背景色
        g.setColor(Color.PINK);
        g.fillRect(1, 1, width - 2, height - 2);
    
        // 添加字样
        Random rm = new Random();
        g.setColor(Color.BLUE);
        g.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 18));
        int position = 20;
        for (int i = 0; i < 4; i++) {
            g.drawString(rm.nextInt(10) + "", position, 20);
            position += 20;
        }
    
        // 加入干扰线
        g.setColor(Color.BLACK);
        for (int i = 0; i < 9; i++) {
            g.drawLine(rm.nextInt(width), rm.nextInt(height), rm.nextInt(width), rm.nextInt(height));
        }
    
        // 以流的方式响应给客户端
        ImageIO.write(img, "jpg", response.getOutputStream());
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容