@WebServlet("/captche")
public class CaptcheController extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletOutputStream sos= resp.getOutputStream();//输出二进制信息
/* resp.getWriter();输出文本信息*/
ImageIO.write(generatePic(100,80),"JPEG",sos);
sos.flush();
sos.close();
}
private BufferedImage generatePic(int width,int height){
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
Graphics g= image.getGraphics();
g.setColor(Color.white);
g.fillRect(0,0,width,height);
g.setColor(Color.black);
//设置字体大小
g.setFont(new Font("宋体",Font.BOLD,26));
//设置验证码的内容,因为我也不是很会,所以就用最低级的静态验证码了
g.drawString("1234",50,20);
Random rnd=new Random();//产生随机数
rnd.nextInt(100);//产生随机数
Graphics2D g2 = image.createGraphics();
Random random = new Random();
g2.setColor(Color.blue);// 设置线条的颜色
//开始增加干扰项,连续做了三个不一样的颜色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(width- 1);
int y = random.nextInt(height- 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
g2.setColor(Color.cyan);
for (int i = 0; i < 20; i++) {
int x = random.nextInt(width- 3);
int y = random.nextInt(height- 3);
int xl = random.nextInt(4) + 2;
int yl = random.nextInt(10) + 2;
g2.drawLine(x, y, x + xl + 30, y + yl + 10);
}
g2.setColor(Color.red);
for (int i = 0; i < 20; i++) {
int x = random.nextInt(width- 6);
int y = random.nextInt(height- 6);
int xl = random.nextInt(1) + 1;
int yl = random.nextInt(2) + 1;
g2.drawLine(x, y, x + xl + 50, y + yl + 40);
}
g.setFont(new Font("宋体",Font.BOLD,26));//设置字体
g.dispose();
return image;
}
}
成品就是这样的了