package com.su.servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.List; 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 CheckCode extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; public static final int WIDTH = 120;//生成圖片的寬度 public static final int HEIGHT = 30;//生成圖片的高度 @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //在內存中建立一張圖片 BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); //獲得圖片 Graphics graphics = bi.getGraphics(); //設置圖片的背景色 graphics.setColor(Color.white); graphics.fillRect(0, 0, WIDTH, WIDTH); //設置圖片的邊框 graphics.setColor(Color.RED); graphics.drawRect(1, 1, WIDTH-2, HEIGHT-2); Color[] color={Color.BLACK,Color.BLUE,Color.CYAN,Color.GREEN, //定義顏色數組 Color.ORANGE,Color.YELLOW,Color.RED,Color.PINK,Color.LIGHT_GRAY}; //圖片上畫干擾線 graphics.setColor(Color.BLUE); //設置線條個數並畫線 for(int i=0;i<10;i++){ graphics.setColor(color[new Random().nextInt(9)]); int x1 = new Random().nextInt(WIDTH); int x2 = new Random().nextInt(WIDTH); int y1 = new Random().nextInt(HEIGHT); int y2 = new Random().nextInt(HEIGHT); graphics.drawLine(x1, y1, x2, y2); } StringBuilder sb = new StringBuilder(); //把隨機數寫在圖片上 graphics.setColor(Color.GRAY); graphics.setFont(new Font("楷體", Font.BOLD, 20)); Graphics2D g = (Graphics2D)graphics; // 控制字數 String str ="0123456789ABCDEFGHIGKLMNOPQRSTUVWRST"; int x = 5; for (int i = 0; i < 4; i++) { // 設置字體旋轉角度 int degree = new Random().nextInt() % 30; char ch = str.charAt(new Random().nextInt(36)); sb.append(String.valueOf(ch)); // 正向角度 g.rotate(degree * Math.PI / 180, x, 20); graphics.drawString(String.valueOf(ch), x, 20); // 反向角度 g.rotate(-degree * Math.PI / 180, x, 20); x += 30; } //7.將隨機數存在session中 request.getSession().setAttribute("checkCode", sb.toString()); //8.設置響應頭通知瀏覽器以圖片的形式打開 response.setContentType("image/jpeg"); //9.設置響應頭控制瀏覽器不要緩存 response.setDateHeader("expries", -1); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); //10.將圖片寫給瀏覽器 ImageIO.write(bi, "jpg", response.getOutputStream()); } }