Java实现简易验证码
使用Java 的 图片IO流对象 ,实现一个在一个图片对象的基础上进行 写字符串, 画像, 等
@WebServlet("/checkcode")
public class CheckCode extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Image对象的高度和宽度
int width = 100;
int height = 50;
//1.创建一对象,在内存中图片(验证码图片对象): 默认使用黑色进行填充
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//3.填充图片
//获取画笔对象: 画笔用来进行填充,画画, 写字符串
final Graphics graphics = image.getGraphics();
//设置画笔颜色
graphics.setColor(Color.ORANGE);
//填充颜色
graphics.fillRect(0,0,width-1 , height-1);
//画边框
graphics.setColor(Color.blue);
graphics.drawRect(0,0,width - 1, height - 1);
//随机字符串: 进行随机验证码的字符串
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
//随机颜色: Color 类的一些常用变量
Color[] colors = {Color.BLACK , Color.BLUE , Color.CYAN , Color.DARK_GRAY , Color.GRAY , Color.GREEN , Color.MAGENTA , Color.ORANGE, Color.RED, Color.WHITE , Color.WHITE , Color.PINK} ;
//写验证码
Random random = new Random();
int index = 0 ;
//写4个字符
for (int i = 1; i <= 4; i++) {
//获取下标
index = random.nextInt(str.length());
//随机颜色:
graphics.setColor(colors[random.nextInt(colors.length)]);
//写验证码: 在图片上写字符
graphics.drawString(""+str.charAt(index), width /5 * i, height / 2);
}
//画干扰线
for (int i = 0; i < 10 ; i++) {
//起始坐标
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
//结束坐标
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
//设置划线颜色
graphics.setColor(colors[random.nextInt(colors.length)]);
graphics.drawLine(x1 ,y1 , x2 , y2);
}
//3.将图片输出到页面展示: 输出源, 输出图片格式, 输出流
ImageIO.write(image,"jpg",response.getOutputStream());
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
程序代码实现了, 随机字符, 随机字符颜色, 随机线条, 随机线条颜色, 随机位置的要求, 总结一下步骤:
- 创建一个图片buffer 对象。用来存放图片, 将图片对象放置在内存中
- 填充图片: 填充背景颜色, 边框等
- 在图片中写入一个字符
- 在图片中画一条线
- 在图片中随机写4个字符
- 在图片中画一定数量的线条
- 使线条起始,结束位置随机, 字符随机位置排列
如果在创建出来的图片无法在页面中显示, 请尝试使用IE, 火狐等浏览器 ,
效果图: