java验证码图片
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()); } }