首先创建图片对象
设置好图片的宽度100和高度50
使用 BufferedImage创建图片对象
@WebServlet("/YanZhengServlet")
public class YanZhengServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 100;
int height = 50;
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//将验证码输出到页面
ImageIO.write(image,"jpg",response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
其次设置验证码的背景色
步骤:
1、获取画图工具对象Graphics g = image.getGraphics();
2、设置颜色 g.setColor(Color.PINK);
3、进行背景填充g.fillRect(0,0,width,height);
Graphics g = image.getGraphics();
g.setColor(Color.PINK);
g.fillRect(0,0,width,height);
设置显示验证码
g.setColor(Color.MAGENTA);
g.drawString("A",20,25);
g.drawString("B",40,25);
g.drawString("C",60,25);
g.drawString("D",80,25);
效果展示:
![](https://img.haomeiwen.com/i15702313/efc9281e9421a4bc.png)
进阶操作:随机生成验证码
首先将字母大小写和数字都存在一个字符串中,然后随机生成一个index,获取对应的字符。再写入到验证码图片中。
String S="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (int i = 1; i <= 4; i++) {
Random random = new Random();
int index = random.nextInt(S.length());
char c = S.charAt(index);
g.drawString(c+"",width/5*i,height/2);
}
![](https://img.haomeiwen.com/i15702313/1a4513c4b2ade7a8.gif)
混淆视觉(干扰线)
绘制一些线段来模拟遮挡验证码的混淆视觉效果
g.setColor(Color.GREEN);
for (int i = 0; i < 10; i++) {
Random random = new Random();
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
g.drawLine(x1,x2,y1,y2);
}
效果展示:
![](https://img.haomeiwen.com/i15702313/cc1f296898e19f25.gif)
网友评论