public class CaptcheController extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//创建一个向客户端返回的通道
ServletOutputStream sos= resp.getOutputStream();
//往通道里放图片
ImageIO.write(generatePic(150,100),"JPEG",sos);
sos.flush();
sos.close();
}
private BufferedImage generatePic(int width,int height)
{
//创建一个可以存图片的对象
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//创建画笔
Graphics g=image.createGraphics();
g.setColor(Color.white);
//填充矩形
g.fillRect(0,0,width,height);
g.setFont(new Font("Times New Roman",Font.PLAIN,18));
//产生随机数
Random rnd=new Random();
g.setColor(Color.BLACK);
//画边框
g.drawRect(0,0,width-1,height-1);
g.setColor(Color.lightGray);
//产生干扰线条
for(int i=0;i<160;i++)
{
int x=rnd.nextInt(width);
int y=rnd.nextInt(height);
int x1=rnd.nextInt(120);
int y1=rnd.nextInt(120);
g.drawLine(x,y,x+x1,y+y1);
}
//随机产生四个数字作为验证码
for(int i=0;i<4;i++)
{
String StrRand=String.valueOf(rnd.nextInt(10));
Color color=new Color(rnd.nextInt(256),rnd.nextInt(256),rnd.nextInt(256));
g.setColor(color);
g.drawString(StrRand,13*i+width/3,height/2);
}
return image;
}
}