您的位置:首页 > Web前端

使用servlet生成图片验证码

2012-08-19 15:38 323 查看
  以前觉得做图片验证码是个很复杂的事情,关键问题是没有想清楚到底是怎样实现的,今天看javaweb王者归来的时候看到了这个方法,于是记录下来,供以后使用。

      将核心代码写一下吧。

      首先是要使用到的字符,

     public static final char CHARS{'2','3'....};这个自己定义就好了,尽量不要出现不好区分的字母,像0和o。

    然后定义一个随机数类,Random random=new Random();

   定义一个生成随即序列的方法。

public static String getString()

{

  StringBuffer buffer=new StringBuffer();

  for(int i=0;i<6;i++)

  buffer.append(CHARS[random.nextInt(CHARS.length)]);

return buffer.toString();

}

定义生成颜色的类

public static Color getColor()

{

  return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));

}

获取颜色的反色

public static Color getReverseColor(Color cc)

{

 return new Color(255-cc.getRed(),255-cc.getGreen(),255-cc.getBlue());

}

 在doGet或者是doPost方法中操作

response.setContentType("image/jpge");

String string=getString();

request.getSession(true).setAttribute("string",string);

int width=100;

int height=30;

Color color=getColor();

Color reverse=getReverseColor(color);

BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

Graphics2D gg=bi.createGraphics();

gg.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16));

gg.setColor(color);

gg.fillRect(0,0,width,height);

gg.serColor(reverse);

gg.drawString(string,18,20);

//加入一些噪声,不超过100个

for(int i=0,n=random.nextInt(100);i<n;i++)

gg.drawRect(random.nextInt(width),random.nextInt(height),1,1);

ServletOutputStream out=response.getOutputStream();

JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);

encoder.encode(bi);

out.flush();

然后直接访问这个servlet就可以了,因为一些原因,我没有办法粘贴源代码,这些都是敲进去的。还是直接参考书上的代码可能会更全些吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息