1. 步骤
- 利用BufferedImage对象在内存中创建图片对象。
- 美化图片
- 获取画笔
- 设置颜色
- 填充背景色用fill/画图用draw
- 用ImageIO.write()方法传输图片
2. 效果
3. 代码
(1)ResponseServlet.java
@WebServlet("/responseServlet")
public class ResponseServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 在内存中方创建图片对象
int width = 200;
int height = 100;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//2.美化图片
//2.1 填充图片背景色
Graphics g = image.getGraphics(); //获取画笔
g.setColor(Color.PINK);
g.fillRect(0, 0, width, height);
//2.2 画矩形边框
g.setColor(Color.BLACK);
g.drawRect(0, 0, width-1, height-1);
//2.3 画文字
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
for (int i = 0; i < 4; i++) {
int index = random.nextInt(str.length());
char c = str.charAt(index);
g.setColor(Color.BLUE);
g.drawString(c+"", width/5*(i+1), height/2);
}
//2.4 画干扰线
for (int i = 0; i < 6; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
g.setColor(Color.green);
g.drawLine(x1, y1, x2, y2);
}
//3.传输图片
ImageIO.write(image, "png", response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
new Date();
}
}
(2)regist.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
window.onload = function () {
//1.为图片绑定事件
var img = document.getElementById("check");
img.onclick = function () {
//获取时间戳
var time = new Date().getTime();
img.src = "/day7/responseServlet?"+time; //如果请求路径不变,会返回302,加载缓存中的数据,图片不变
}
//2.为超链接绑定事件
var change = document.getElementById("change");
change.onclick = function () {
//获取时间戳
var time = new Date().getTime();
img.src = "/day7/responseServlet?"+time;
}
}
</script>
</head>
<body>
<img id="check" src="/day7/responseServlet">
<a id="change" href="">看不清,换一张</a>
</body>
</html>