response 画验证码
代码
import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; 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 ValiImage extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width = 150; int height = 50; BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) image.getGraphics(); //添加背景颜色 g.setColor(Color.GRAY); g.fillRect(0,0,width,height); //添加边框 g.setColor(Color.black); g.drawRect(0,0,width-1,height-1); //画干扰线 int count = 10; while(count>0) { g.setColor(Color.RED); g.drawLine(RandomNum(0,width), RandomNum(0,height),RandomNum(0,width), RandomNum(0,height)); count--; } //画字体 for(int p = 0 ; p < 4; p++) { g.setColor(new Color(RandomNum(0,255),RandomNum(0,255),RandomNum(0,255))); g.setFont(new Font("黑体",Font.BOLD,20)); g.drawString("中",5+(p*37),25); } ImageIO.write(image,"jpg",response.getOutputStream()); } private Random rand = new Random(); public int RandomNum(int i,int j) { //返回一个大于i小于j的随机数 //return rand.nextInt(j-i)+i; return i+(int)(Math.random()*j); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }