导读:常用的验证码有文本+数字,或者是算式验证码。可以自己编写,来生成验证码。亦或是使用第三方库,来生成验证码。
字母数字验证码
实现形如下图的验证码:
编写一个验证码生成类,首先写一个产生随机字符的方法:
public class CaptchaCode {
private static char randomChar(){
String string="QWERTYUIOPASDFGHJKLZXCVBNM1234567890";
Random random=new Random();
return string.charAt(random.nextInt(string.length()));
}
}
然后写一个生成验证码图片的方法:
public static String drawImage(HttpServletResponse response){
//1.拼接字符串的类
StringBuilder builder=new StringBuilder();
//产生4位验证码
for (int i = 0; i <4 ; i++) {
builder.append(randomChar());
}
String code=builder.toString();
//2.定义图片的宽度和高度
int width=120;
int height=25;
//建立BufferedImage对象,指定图片缓冲流的长宽度和样式
BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
//3.获取Graphics2d绘制对象,开始绘制验证码。图片最终会注入到缓冲流中
Graphics2D graph=bi.createGraphics();
//4.设置字体和大小
Font font=new Font("宋体",Font.PLAIN,20);
Color color=new Color(0,255,255);
graph.setFont(font);
graph.setColor(color);
graph.setBackground(new Color(0,0,0));
//绘制形状,一般是矩形
graph.clearRect(0,0,width,height);
//创建字体对象
FontRenderContext context=graph.getFontRenderContext();
//获得文字的边界
Rectangle2D bounds=font.getStringBounds(code,context);
//计算坐标和间距,以便字体放在矩形的正中央
double x=(width-bounds.getWidth())/2;
double y=(height-bounds.getHeight())/2;
double acsent=bounds.getY();
double baseY=y-acsent;
//在矩形中绘制字体
graph.drawString(code,(int)x,(int)baseY);
graph.dispose();
//保存到响应的输出流
try {
ImageIO.write(bi,"jpg",response.getOu