新建一个Servlet
在doGet或者doPost方法中提供下面的代码。
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);
//创建一个画笔
Graphics g = img.getGraphics();
//给图片添背景颜色
g.setColor(Color.PINK);
//填充面积减去边框的大小
g.fillRect(1,1, width-2, height-2);
//给边框添加颜色
g.setColor(Color.RED);
g.drawRect(0,0, width-1, height-1);
//设置文本样式
g.setColor(Color.BLUE);
g.setFont(new Font("宋体",Font.BOLD|Font.ITALIC,15));
//给图片添加文本内容,验证码上面的文字
/*
* 第一个参数:内容
* 第二个参数:上距离
* 第三个参数:左距离
*/
//显示的内容生成4位的随机数
Random rand = new Random();
int position = 20;
for(int i = 0;i < 4;i++){
int count = rand.nextInt(10);
g.drawString(count+"", position,20);
position = position+20;
}
//将图片对象以流的方式输出到客户端
ImageIO.write(img, "jpg",response.getOutputStream());
//
}
效果演示: