import java.awt.image.BufferedImage; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ResponseDemo4 extends HttpServlet { public static final int WIDTH = 120; public static final int HEIGHT = 35; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); // 设置背景色 setBackGround(g); // 设置边框 setBored(g); // 画干扰线 drawRandomLine(g); // 写随机数字 drawRandowNum((Graphics2D) g); // 图形写给浏览器 response.setContentType("image/jpeg"); // 控制浏览器不要拿缓存 response.setDateHeader("expries", -1); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); ImageIO.write(image, "jpg", response.getOutputStream()); } public void drawRandowNum(Graphics2D g) { g.setColor(Color.RED); g.setFont(new Font("黑体", Font.BOLD, 20)); String base = "u7684u4e00u662fu4e86u6211u4e0du4ebau5728u4ed6u6709u8fd9u4e2au4e0au4eecu6765 u5230u65f6u5927u5730u4e3au5b50u4e2du4f60u8bf4u751fu56fdu5e74u7740u5c31u90a3 u548cu8981u5979u51fau4e5fu5f97u91ccu540eu81eau4ee5u4f1au5bb6u53efu4e0bu800cu8fc7u5929u53bbu80fdu5bf9u5c0fu591au7136u4e8eu5fc3u5b66u4e48u4e4bu90fdu597du770bu8d77u53d1u5f53u6ca1u6210u53eau5982u4e8bu628au8fd8u7528u7b2cu6837u9053 u60f3u4f5cu79cdu5f00u7f8eu603bu4eceu65e0u60c5u5df1u9762u6700u5973u4f46u73b0 u524du4e9bu6240u540cu65e5u624bu53c8u884cu610fu52a8u65b9u671fu5b83u5934u7ecf u957fu513fu56deu4f4du5206u7231u8001u56e0u5f88u7ed9u540du6cd5u95f4u65afu77e5"; int x = 5; for (int i = 0; i < 4; i++) { int degree = new Random().nextInt() % 30; // 旋转-30°到30° String ch = base.charAt(new Random().nextInt(base.length())) + ""; g.rotate(degree * Math.PI / 180, x, 20); // 设置旋转的弧度 g.drawString(ch, x, 20); g.rotate(-degree * Math.PI / 180, x, 20); x += 30; } } public void setBored(Graphics g) { g.setColor(Color.GRAY); g.fillRect(1, 1, WIDTH - 2, HEIGHT - 2); } public void drawRandomLine(Graphics g) { g.setColor(Color.GREEN); for (int i = 0; i < 4; i++) { int x1 = new Random().nextInt(WIDTH); int y1 = new Random().nextInt(HEIGHT); int x2 = new Random().nextInt(WIDTH); int y2 = new Random().nextInt(HEIGHT); g.drawLine(x1, y1, x2, y2); } } public void setBackGround(Graphics g) { g.setColor(Color.WHITE); g.fillRect(0, 0, WIDTH, HEIGHT); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }