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
Title
看不清,换一张