1 package com.cgyue; 2 3 import java.awt.Color; 4 import java.awt.Font; 5 import java.awt.Graphics; 6 import java.awt.image.BufferedImage; 7 import java.io.IOException; 8 import java.util.Random; 9 10 import javax.imageio.ImageIO; 11 import javax.servlet.ServletException; 12 import javax.servlet.http.HttpServlet; 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 16 /** 17 * 生成图形验证码的Servlet 18 */ 19 public class ImageCodeMakerServlet extends HttpServlet { 20 21 public void doGet(HttpServletRequest request, HttpServletResponse response) 22 throws ServletException, IOException { 23 doPost(request, response); 24 } 25 26 /** 27 * @see javax.servlet.http.HttpServlet#void 28 * (javax.servlet.http.HttpServletRequest, 29 * javax.servlet.http.HttpServletResponse) 30 */ 31 public void doPost(HttpServletRequest request, HttpServletResponse response) 32 throws ServletException, IOException { 33 // 首先设置页面不缓存 34 response.setHeader("Pragma", "No-cache"); 35 response.setHeader("Cache-Control", "no-cache"); 36 response.setDateHeader("Expires", 0); 37 38 // 定义图片的宽度和高度 39 int width = 90, height = 40; 40 // 创建一个图像对象 41 BufferedImage image = new BufferedImage(width, height, 42 BufferedImage.TYPE_INT_RGB); 43 // 得到图像的环境对象 44 Graphics g = image.createGraphics(); 45 46 Random random = new Random(); 47 // 用随机颜色填充图像背景 48 g.setColor(getRandColor(180, 250)); 49 g.fillRect(0, 0, width, height); 50 for (int i = 0; i < 5; i++) { 51 g.setColor(getRandColor(50, 100)); 52 int x = random.nextInt(width); 53 int y = random.nextInt(height); 54 g.drawOval(x, y, 4, 4); 55 } 56 // 设置字体,下面准备画随机数 57 g.setFont(new Font("", Font.PLAIN, 40)); 58 // 随机数字符串 59 String sRand = ""; 60 for (int i = 0; i < 4; i++) { 61 // 生成四个数字字符 62 String rand = String.valueOf(random.nextInt(10)); 63 sRand += rand; 64 // 生成随机颜色 65 g.setColor(new Color(20 + random.nextInt(80), 20 + random 66 .nextInt(100), 20 + random.nextInt(90))); 67 // 将随机数字画在图像上 68 g.drawString(rand, (17 + random.nextInt(3)) * i + 8, 34); 69 70 // 生成干扰线 71 for (int k = 0; k < 12; k++) { 72 int x = random.nextInt(width); 73 int y = random.nextInt(height); 74 int xl = random.nextInt(9); 75 int yl = random.nextInt(9); 76 g.drawLine(x, y, x + xl, y + yl); 77 } 78 } 79 80 // 将生成的随机数字字符串写入Session 81 request.getSession().setAttribute("randcode", sRand); 82 // 使图像生效 83 g.dispose(); 84 // 输出图像到页面 85 ImageIO.write(image, "JPEG", response.getOutputStream()); 86 } 87 88 /** 89 * 产生一个随机的颜色 90 * @param fc 颜色分量最小值 91 * @param bc 颜色分量最大值 92 * @return 93 */ 94 public Color getRandColor(int fc, int bc) { 95 Random random = new Random(); 96 if (fc > 255){ 97 fc = 255; 98 } 99 if (bc > 255){ 100 bc = 255; 101 } 102 int r = fc + random.nextInt(bc - fc); 103 int g = fc + random.nextInt(bc - fc); 104 int b = fc + random.nextInt(bc - fc); 105 return new Color(r, g, b); 106 } 107 }