---
title: "Servlet生成彩色验证码"
author: "knight"
date: "2007-04-19T11:18:13Z"
tags: []
slug: "servlet"
draft: false
lastmod: "2007-04-19T11:18:13Z"
id: 72410
url: "https://knight.iteye.com/blog/72410"
---

很早以前用的，为了防止忘记，做个记录

java 代码

01. import java.io.IOException;
02. import javax.servlet.ServletException;
03. import javax.servlet.ServletOutputStream;
04. import javax.servlet.http.HttpServlet;
05. import javax.servlet.http.HttpServletRequest;
06. import javax.servlet.http.HttpServletResponse;
07. import javax.servlet.http.HttpSession;
08. import com.sun.image.codec.jpeg.JPEGCodec;
09. import com.sun.image.codec.jpeg.JPEGImageEncoder;
10. import java.awt.\*;
11. import java.awt.image.\*;
12. import java.util.\*;
13. public class ImageServlet
14. extends HttpServlet {
15. public void doGet(HttpServletRequest request, HttpServletResponse response) throws
16. ServletException, IOException {
17. response.reset();
18. response.setContentType("image/jpeg");
19. response.setHeader("Pragma", "No-cache");
20. response.setHeader("Cache-Control", "no-cache");
21. response.setDateHeader("Expires", 0);
22. //在内存中创建图象
23. int width = 58, height = 18;
24. BufferedImage image = new BufferedImage(width, height,
25. BufferedImage.TYPE\_INT\_RGB);
26. //获取图形上下文
27. Graphics g = image.getGraphics();
28. //生成随机类
29. Random random = new Random();
30. //设定背景色
31. g.setColor(new Color(201 + random.nextInt(50), 201 + random.nextInt(50),
32. 201 + random.nextInt(50)));
33. g.fillRect(0, 0, width, height);
34. //设定字体
35. g.setFont(new Font("Times new Roman", Font.PLAIN, 18));
36. //画边框
37. //g.setColor(new Color());
38. //g.drawRect(0,0,width-1,height-1);
39. //随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
40. g.setColor(new Color(160 + random.nextInt(41), 160 + random.nextInt(41),
41. 160 + random.nextInt(41)));
42. for (int i = 0; i &lt; 155; i++) {
43. int x = random.nextInt(width);
44. int y = random.nextInt(height);
45. int xl = random.nextInt(12);
46. int yl = random.nextInt(12);
47. g.drawLine(x, y, x + xl, y + yl);
48. }
49. //取随机产生的认证码(4位数字)
50. String sRand = "";
51. for (int i = 0; i &lt; 4; i++) {
52. String rand = String.valueOf(random.nextInt(10));
53. sRand += rand;
54. //将认证码显示到图象中
55. g.setColor(new Color(20 + random.nextInt(111), 20 + random.nextInt(111),
56. 20 + random.nextInt(111)));
57. //调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
58. g.drawString(rand, 13 * i + 6, 16);
59. }
60. HttpSession session = null;
61. session = request.getSession(true);
62. //将认证码存入SESSION
63. session.setAttribute("rand", sRand);
64. //图象生效
65. g.dispose();
66. //输出图象到页面
67. //ImageIO.write(image, "JPEG", resp.getOutputStream());
68. //response.setContentType("image/jpeg");
69. ServletOutputStream out = response.getOutputStream();
70. JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
71. encoder.encode(image);
72. out.close();
73. }
74. }