/* * 验证码 * http://blog.csdn.net/strawberry2013 * 2013-6-5 */ package cn.baidu; 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; public class ServletImage extends HttpServlet { private static final int WIDTH = 150; private static final int HEIGHT = 35; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //告诉浏览器不要缓存 response.setDateHeader("expries", -1); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); //设置类型 response.setContentType("image/jpeg"); //新建BufferedImage,通过getGraphics方法得到画板 BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); //将画板的填充为白色 g.setColor(Color.WHITE); g.fillRect(0, 0, WIDTH, HEIGHT); //将画板的边框画上 g.setColor(Color.BLUE); g.drawRect(1, 1, WIDTH-2, HEIGHT-2); //产生随机的线条 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); } //写上字并旋转 g.setColor(Color.RED); g.setFont(new Font("宋体", Font.BOLD, 30)); String str = "请按照网上邪恶的插入法提供必要花奴家米科利"; int x = 5; Graphics2D gg = (Graphics2D) g; for(int i=0; i<4; i++){ int angle = new Random().nextInt(40) -20; //产生随机的角度 gg.rotate(angle*Math.PI/180, x, 30); //旋转画板 int start = new Random().nextInt(str.length()); g.drawString(str.substring(start, start+1), x, 25); //写上字 gg.rotate(-angle*Math.PI/180, x, 30); //将画板重新还原 x += 35; } //将image 写入到流中 ImageIO.write(image, "jpg", response.getOutputStream()); } }