一、验证码的产生
1.验证码的产生:在本程序中生成的验证码是从事先存储好的汉字中选取,使用Random类获得随机数作为字符串中字符的索引值,并使用String类的substring()方法,从字符串中截取一个汉字作为验证码。
2.substring()方法:使用String类的substring()方法,可截取字符串中的字符,该方法的定义:
public String substring (int beginIndex ,int endIndex);
其中,beginIndex为起始索引(包括),endIndex:结束索引(不包括)。即半开半闭区间:【beginIndex,endIndex)。
二、设计过程:
1.单独建立一个项目;
2.在项目中创建一个继承JFrame类的MyFrame窗体类和一个继承Jpanel类的ChineseCodePanel面板类
3.在面板类中重写JComponent类的paint()方法,在该方法中向BufferedImage对象上绘制中文验证码。
4.面板类的paint()方法如下:
public void paint(Graphics g) {
String HanZi = "胖咸鱼百家号中文验证码面板类测试";// 存储中文验证码的汉字
BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);// 实例化BufferedImage
Graphics gs = image.getGraphics(); // 获取Graphics类的对象
if (!num.isEmpty()) {
num = "";// 清空验证码
}
Font font = new Font("黑体", Font.BOLD, 20); // 通过Font构造字体
gs.setFont(font);// 设置字体
gs.fillRect(0, 0, WIDTH, HEIGHT);// 填充一个矩形
// 输出随机的验证文字
for (int i = 0; i < 4; i++) {
int index = random.nextInt(HanZi.length());// 随机获得汉字的索引值
String ctmp =HanZi.substring(index,index+1);// 获得指定索引处的一个汉字
num += ctmp;// 更新验证码
Color color = new Color(20 + random.nextInt(120), 20 + random
.nextInt(120), 20 + random.nextInt(120));// 生成随机颜色
gs.setColor(color); // 设置颜色
Graphics2D gs2d = (Graphics2D) gs;// 将文字旋转指定角度
AffineTransform trans = new AffineTransform();// 实例化AffineTransform
trans.rotate(random.nextInt(45) * 3.14 / 180, 22 * i + 8, 7);
float scaleSize = random.nextFloat() + 0.8f;// 缩放文字
if (scaleSize > 1f) {
scaleSize = 1f;// 如果scaleSize大于1,则等于1
}
trans.scale(scaleSize, scaleSize); // 进行缩放
gs2d.setTr