import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/check")
public class Demo03 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int width = 500;
int height = 200;
//创建背景图片
BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
Graphics graphics = bufferedImage.getGraphics();
//填充背景
graphics.setColor(Color.lightGray);
graphics.fillRect(0,0,width,height);
//绘制边界
graphics.setColor(Color.blue);
graphics.drawRect(0,0,width-1,height-1);
//设置文字风格
graphics.setFont(new Font("Arial",1,72));
//绘制文字
String str = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890";
Random random = new Random();
int red = 0, green = 0, blue = 0;
graphics.setColor(Color.red);
for (int i = 1; i <= 4; i++) {
int index = random.nextInt(str.length());
char ch = str.trim().charAt(index);
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
// 用随机产生的颜色将验证码绘制到图像中。
graphics.setColor(new Color(red, green, blue));
graphics.drawString(ch+"",width/6*i-2,height/2+6);
}
//绘制干扰
for (int i = 0; i < 10; i++) {
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
// 用随机产生的颜色将验证码绘制到图像中。
graphics.setColor(new Color(red, green, blue));
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
graphics.drawLine(x1,y1,x2,y2);
}
ImageIO.write(bufferedImage,"png",resp.getOutputStream());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
}
java验证码
最新推荐文章于 2024-04-27 10:33:44 发布