下面是自己写的一个生成验证码的代码:
1.4个验证码不在同一位置,
2.美观度可以自己改变。全部由自己设计,
package cn.itcast.zlWeb.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.Random;
public class Helper {
/**
* 生成一个验证码图片
*
* @param width
* 图片宽度
* @param height
* 图片高度
* @return
*/
public static BufferedImage getImage(int width, int height)
{
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_3BYTE_BGR);
Graphics g = image.getGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, width, height);
// 干扰点
g.setColor(Color.BLUE);
Random r = new Random();
for (int i = 0; i < 100; i++) {
int x = r.nextInt(width) - 2;
int y = r.nextInt(height) - 2;
// 画图片上的点
g.drawOval(x, y, width, height);
}
// 写验证码
char[] arrays = ("123456789abcdefghijklmnopqrstuvwxyz"
+ "HIJKLMNOPQRSTUVWXYZ").toCharArray();
g.setColor(Color.RED);
// 得到验证码
//StringBuilder sb = new StringBuilder();
g.setFont(new Font("微软雅黑",Font.BOLD,20));
int x = 20;
int y = 0;
for (int i = 0; i < 4; i++) {
int pos = r.nextInt(arrays.length);
char c = arrays[pos]; //取的随机码
y = r.nextInt(20)+10;
x += r.nextInt(20)+5;
g.drawString(c+"", x, y);
}
return image;
}
}