package cn.lijun; 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.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 生成随机图片,即为验证码的生成(BufferImage(jdkApi内存图片)) * 为了防止编程实现图片识别验证码,而产生的恶意注册,登陆。 * 生产的验证码图片需要以下要求: * 1.底色 * 2.随机数 * 3.干扰线 * 4.字符旋转 * @author Administrator * */ public class ResponseRandomPic extends HttpServlet { public static final int WIDTH = 120; public final static int HEIGHT = 25 ; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); //1.设置背景色 setBackGround(g); //2.设置图形边框 setBorder(g); //3.画干扰线 drawRandomLine(g); //4.给图形生成随机文字 drawRandomNum(g); //5.把图形写给浏览器 response.setContentType("image / jpeg"); ImageIO.write(image, "jpg", response.getOutputStream()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } private void drawRandomNum(Graphics g) { Graphics2D g2d = (Graphics2D) g; // 生成随机数 final char randomStr[] = {'a' ,'b' ,'c','d','e' , 'f' ,'g' , 'h','i','j' , 'k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; final int len = 6; g2d.setColor(Color.RED); g2d.setFont(new Font("宋体",Font.BOLD , 20)); int x = 10; for(int i = 0 ; i < len ; i ++ ){ String ranStr = ""; int y = new Random().nextInt(5)+17; System.out.println("y:"+y); ranStr = randomStr[new Random().nextInt(26)]+""; //随机旋转(30度以内旋转) int degree = new Random().nextInt()%30;//生成-30-30的随机数 g2d.rotate(degree*Math.PI/180, x, y); //为了不影响下一个字的旋转,把图片旋转回去(重置旋转) g2d.rotate(-degree*Math.PI/180, x, y); g2d.drawString(ranStr,x ,y); x +=17; } } private void drawRandomLine(Graphics g) { // TODO Auto-generated method stub g.setColor(Color.green); for(int i = 0 ; i < 5 ; 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); } } private void setBorder(Graphics g) { // TODO Auto-generated method stub g.setColor(Color.BLUE); g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2); } private void setBackGround(Graphics g) { // 设置背景色 g.setColor(Color.WHITE); g.fillRect(0, 0, WIDTH,HEIGHT); } } 以下为前台js代码:
<img src="/servletStu/ResponseRandom.action" onclick="this.src = this.src ?new Date().getTime()" style="cusor:hand"/>
原文地址:http://blog.csdn.net/u010218226/article/details/44306555