主要用来了解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());
}
05-11 15:02