-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcaptcha
More file actions
68 lines (54 loc) · 2.09 KB
/
Copy pathcaptcha
File metadata and controls
68 lines (54 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package test.captcha;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 生成验证码
* @author striner
*
*/
public class Captcha extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 110;
int height = 25;
//在内存中创建一个图像对象
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //RGB:三原色
//创建一个画笔
Graphics g = img.getGraphics();
//给图片添加背景色
g.setColor(Color.PINK); //设置颜色
g.fillRect(1, 1, width-2, height-2); //设置边框显示坐标 g.fillRect(上, 右, 下, 左)
//给边框一个色
//g.setColor(Color.GRAY);
g.setColor(Color.CYAN); //CYAN: 浅蓝色
g.fillRect(0, 0, width-1, height-1);
//设置文本样式
g.setColor(Color.BLUE);
g.setFont(new Font("宋体", Font.BOLD|Font.ITALIC, 15)); //Font.BOLD:加粗 Font.ITALIC:斜体
//给图片添加文本
Random rand = new Random();
int position = 20; //第一个数字的横坐标
for (int i = 0; i < 4; i++) { //随机产生四个数字
g.drawString(rand.nextInt(10)+"", position, 20); //drawString(String, int, int) 给图片填充文本
position += 20; //每两个数之间横间距为20px
}
//添加9条干扰线
for(int i = 0; i < 9; i++) {
g.drawLine(rand.nextInt(width), rand.nextInt(height), rand.nextInt(width), rand.nextInt(height));
}
//将图片对象以流的方式输出到客户端
ImageIO.write(img, "jpg", response.getOutputStream());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}