java servlet 里写一个验证码

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  /**
* 在内存中生成图片(纸),没有设置背景颜色,画填充的矩形,并且和纸的大小相同,矩形有颜色。
* 获取笔的对象(设置颜色,设置字体,画字符串,画矩形)
* 先准备好数据,随机生成4个字符,把字符画到纸上
* 画干扰线
* 把内存中的图片输出到客户端上
*/
int width = 120;
int height = 30;
// 在内存中生成图片
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.BLUE);
// 画边框
g.drawRect(0, 0, width-1, height-1);
// 准备数据,随机获取4个字符
String words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
       // 设置颜色
g.setColor(Color.YELLOW);
// 设置字体
g.setFont(new Font("隶书", Font.BOLD, 20));

Random random = new Random();
int x = 20;
int y = 20;
for(int i=0;i<4;i++){

// void rotate(double theta, double x, double y)  
// theta 弧度
// hudu = jiaodu * Math.PI / 180;
// 获取正负30之间的角度
int jiaodu = random.nextInt(60)-30;
double hudu = jiaodu * Math.PI / 180;
g.rotate(hudu, x, y);
// 获取下标
int index = random.nextInt(words.length());
// 返回指定下标位置的字符,随机获取下标
char ch = words.charAt(index);
// 写字符串
g.drawString(""+ch, x, y);

g.rotate(-hudu, x, y);
x += 20;
}

// 设置颜色
g.setColor(Color.GREEN);
int x1,x2,y1,y2;
// 画干扰线
for(int i=0;i<4;i++){
x1 = random.nextInt(width);
y1 = random.nextInt(height);
x2 = random.nextInt(width);
y2 = random.nextInt(height);
g.drawLine(x1, y1, x2, y2);
}

// 输出到客户端
ImageIO.write(image, "jpg", response.getOutputStream());
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangkaixuan456

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值