1 //生成图片响应流,返回给客户端
2 //之前是text/html
3 //a.设置响应类型为图片
4 response.setContentType("image/jpeg");
5 //b.创建出图片对象 BufferedImage(0, 0, 0):参数1图片宽度 参数2图片高度 参数3 图片的像素
6 BufferedImage image = new BufferedImage(70, 30, BufferedImage.TYPE_INT_RGB);
7 Graphics g = image.getGraphics();//获取该图片对象的画笔对象
8 //c.画背景 设置灰色背景
9 g.setColor(Color.GRAY);
10 g.fillRect(0, 0, 70, 30);//通过填充矩形的方式,将整个画的内容填满
11 //d.画字符串
12 //随机生成5位数的数字字符串
13 Random r = new Random();
14 int num = r.nextInt(100000-10000)+10000; //10000~99999
15 String code =String.valueOf(num);//转换成字符串
16 //将生成的字符串验证码放入session中 绑定到code属性上
17 HttpSession session = request.getSession();
18 session.setAttribute("code", code);
19
20 //设置字体颜色,设置字体
21 g.setColor(Color.BLUE);
22 g.setFont(new Font("Consolas",Font.BOLD,20));
23 //将字符串画在内存中的图片对象上
24 g.drawString(code, 5, 20);
25 //画一些线条,增加破解难度
26 g.setColor(Color.BLACK);
27 g.drawLine(r.nextInt(70),r.nextInt(30),r.nextInt(70),r.nextInt(30));
28 g.drawLine(r.nextInt(70),r.nextInt(30),r.nextInt(70),r.nextInt(30));
29 g.drawLine(r.nextInt(70),r.nextInt(30),r.nextInt(70),r.nextInt(30));
30 g.drawLine(r.nextInt(70),r.nextInt(30),r.nextInt(70),r.nextInt(30));
31
32 //e.将图片对象通过流的方式响应回给页面
33 //write(im, formatName, output): im是图片对象 formatName 是设置图片的格式 output是输出流对象
34 ImageIO.write(image, "JPEG", response.getOutputStream());