最近做项目做到了
从八百年前的破烂项目里掏出来用
生成验证码图片
public class CreateCodeimg {
public static BufferedImage getCodeImg(HttpServletRequest request){
BufferedImage iamg=null;
int width = 80,height = 40;
iamg = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
Graphics g_img = iamg.getGraphics();
g_img.setColor(Color.WHITE);
g_img.fillRect(0,0,width,height);
String str = "123456789zxcvbnmasdfghjklqwertyuiopZXCVBNMASDFGHJKLQWERTYUIOP";
Random ran = new Random();
String codeStr="";
HttpSession session = request.getSession();
for(int i = 1;i<=4;i++){
int index= ran.nextInt(str.length());
char ch =str.charAt(index);
codeStr =codeStr+ch;
}
session.removeAttribute("RANDOMCODEKEY");
// 往session中存放随机生成的字符串
session.setAttribute("RANDOMCODEKEY", codeStr);
g_img.setColor(Color.BLUE);
g_img.setFont(new Font(null,Font.ITALIC,20));
g_img.drawString(codeStr,13,20);
for (int i = 0; i < 150; i++) {
int x = ran.nextInt(width);
int y = ran.nextInt(height);
g_img.drawOval(x,y,1,1);
}
return iamg;
}
}
在servlet中使用
BufferedImage image = CreateCodeimg.getCodeImg(request);
ImageIO.write(image,"jpg",response.getOutputStream());