自定义验证码实现程序代码:
ImageUtils类:
package util;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.qizhi.common.Global;
/**
* 产生验证码
*/
public class ImageUtils {
// 声明产生颜色的方法
public static Color getRandColor(int beginVal, int endVal) {
Random random = new Random();
if (beginVal > 255)
beginVal = 255;
if (endVal > 255)
endVal = 255;
int r = beginVal + random.nextInt(endVal - beginVal);
int g = beginVal + random.nextInt(endVal - beginVal);
int b = beginVal + random.nextInt(endVal - beginVal);
return new Color(r, g, b);
}
public static boolean getValidImage(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// 声明图片的宽和高
int width = 81, height = 20;
// 创建一个图片缓存对象
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 声明一个图形设备,通过它在图片上绘制图形
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
// 用设置的颜色填充矩形区域
g.fillRect(0, 0, width, height);
g.setFont(new Font("宋体", Font.PLAIN, 25));
// 画出干扰线
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++)// 线的密码
{
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
// 产生四位验证码
String sRand = "";
String u = "QWERTYUIOPLKJHGFDSAZXCVBNM";
char[] CH = u.toCharArray();
char[] ch = u.toLowerCase().toCharArray();
for (int i = 0; i < 4; i++) {
String rand = null;
int fag = random.nextInt(3);
if (fag == 0)
rand = String.valueOf(random.nextInt(10));
if (fag == 1)
rand = String.valueOf(ch[random.nextInt(26)]);
if (fag == 2)
rand = String.valueOf(CH[random.nextInt(26)]);
// 得到验证码
sRand += rand;
// 设置每位验证码颜色
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
// 画出每一个字符
g.drawString(rand, 17 * i + 4, 20);
}
// 将产生的验证码放SESSION对象中
request.getSession().setAttribute(Global.LOGIN_VALID_NO, sRand);
// 释放资源
g.dispose();
// 获得输出流将其以JPEG格式输出为ImageIO流
boolean success = ImageIO.write(image, "JPEG", response.getOutputStream());
return success;
}
/**
* 获得字符图片
* @param obj
* @return
*/
public static String getPic(int obj) {
String str = "";
for (int i = 0; i < obj; i++) {
str = str + "☆";
}
return str;
}
}
以上代码只需在Servlet或action中调用即可实现验证码。