package com.itheima.controller;
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;
import com.sun.xml.internal.bind.util.Which;
/**
* Servlet implementation class yanzhengmaa
*/
public class yanzhengmaa extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 得到画板
int width = 200;// 设置画板宽
int height = 50;// 设置画板高
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);// 创建画板对象,给定参数
// 长,宽,图片数据的来源(INR_RGB)
// 得到画笔
Graphics g = bi.getGraphics();
//开始吟诗作画~
//画背景
g.setColor(Color.RED);//设置笔颜色为红色,画背景颜色
g.fillRect(0, 0, width, height);//用笔填充矩形(颜色)
//画边框
g.setColor(Color.black);//设置笔的颜色为黑色
g.drawRect(0, 1, width - 1, height - 1 );//参数(开始x,开始y,结束x,结束y)从左上角开始画矩形到右下角. (-1是补齐,因为和数组一样从0开始至x-1实体结束)
g.drawRect(9, 9, width -20, height - 20 );//自发添加二层横框
//画干扰线
Random r = new Random();//创建随机数对象
int count = r.nextInt(10);
for (int i = 0; i < count; i++) {
g.setColor(Color.BLACK);//设置笔的颜色1
g.drawLine(r.nextInt(width-2)+1,r.nextInt(height-2)+1,r.nextInt(width-2)+1, r.nextInt(height-2)+1);//笔,画直线,(x,y,x,y)
g.setColor(Color.BLUE);//设置笔的颜色2
g.drawLine(r.nextInt(width-2)+1,r.nextInt(height-2)+1,r.nextInt(width-2)+1, r.nextInt(height-2)+1);
}
//开始给验证码加字
String[] akc = {"桑","海","嗨","四","行","且","瑞","限","期","骑","啥","赖","傻","奇","哥","验","整","1","级","空","等","穷","怕","了","哦","啊","从","是","去"};//设置验证码字库
g.setColor(Color.CYAN);//设置笔的颜色
g.setFont(new Font("微软雅黑", Font.BOLD, r.nextInt(8)+21));//设置字体(字体,加粗,字号)
int x = 30;//第一个验证码文字开始位置
StringBuilder str = new StringBuilder();
for (int i = 0; i < 4; i++) { //循环四次
String yzm = akc[r.nextInt(akc.length-1)];//每次从akc数组里随机出一个元素值赋值给yzm
str.append(yzm); //将yzm加入到字符缓冲区
g.drawString(String.valueOf(yzm), x, r.nextInt(34)+13);//画出yzm
x+=r.nextInt(41)+10;
}
// 显示出来,使用流输出
ImageIO.write(bi, "jpg", response.getOutputStream());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
达到效果:



该写的都写了,注释也很详细,完全自己敲的.喜欢的可以拿去研究咯!