图片验证码的生成
来源:互联网 发布:大连金斧子软件 编辑:程序博客网 时间:2024/05/29 04:33
1 package util;2 3 import javax.imageio.ImageIO;4 import javax.servlet.ServletException;5 import javax.servlet.http.HttpServlet;6 import javax.servlet.http.HttpServletRequest;7 import javax.servlet.http.HttpServletResponse;8 import java.awt.*;9 import java.awt.image.BufferedImage;10 import java.io.IOException;11 import java.util.Random;12 13 14 20 public class PicCheckCode extends HttpServlet {21 22 private Font mFont = new Font("Arial Black", Font.PLAIN, 15); private int lineWidth = 2; private int width = 60; private int height = 20; private int count = 200;27 28 36 private Color getRandColor(int fc, int bc) { 38 Random random = new Random();39 40 if (fc > 255) {41 42 fc = 255;43 }44 45 if (bc > 255) {46 47 bc = 255;48 }49 50 int r = fc + random.nextInt (bc - fc);51 int g = fc + random.nextInt (bc - fc);52 int b = fc + random.nextInt (bc - fc);53 54 return new Color(r, g, b);55 }56 57 public void doPost(HttpServletRequest request, HttpServletResponse response)59 throws ServletException, IOException {60 61 doGet (request, response);62 }63 64 73 public void doGet(HttpServletRequest request, HttpServletResponse response)74 throws ServletException, IOException {75 76 response.setHeader ("Pragma", "No-cache");79 response.setHeader ("Cache-Control", "no-cache");80 response.setDateHeader ("Expires", 0);81 response.setContentType ("image/gif");82 83 BufferedImage image = new BufferedImage(width, height,85 BufferedImage.TYPE_INT_RGB);86 87 Graphics2D g = (Graphics2D) image.getGraphics ();89 90 Random random = new Random();92 93 g.setColor (getRandColor (200, 250)); 96 g.fillRect (0, 0, width, height);97 98 g.setFont (mFont);100 101 g.setColor (getRandColor (0, 20)); g.drawRect (0, 0, width - 1, height - 1);104 105 for (int i = 0; i < count; i++) {107 108 g.setColor (getRandColor (150, 200)); 110 int x = random.nextInt (width - lineWidth - 1) + 1; int y = random.nextInt (height - lineWidth - 1) + 1;112 int xl = random.nextInt (lineWidth);113 int yl = random.nextInt (lineWidth);114 g.drawLine (x, y, x + xl, y + yl);115 }116 117 String sRand = "";119 120 for (int i = 0; i < 4; i++) {121 122 String rand = String.valueOf (random.nextInt (10));123 sRand += rand;124 125 g.setColor (new Color(20 + random.nextInt (130),127 20 + random.nextInt (130), 20 + random.nextInt (130))); 129 g.drawString (rand, (13 * i) + 6, 16);130 131 132 }133 134 request.getSession ().setAttribute ("getImg", sRand);136 137 g.dispose ();139 140 ImageIO.write (image, "PNG", response.getOutputStream ());142 }143 }144