欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java仿Servlet生成验证码实例详解

程序员文章站 2024-02-28 11:49:16
java仿servlet生成验证码实例详解 实现原理:使用bufferedimage对象的graphics来进行绘制,然后输出成一张图片进行保存 实现代码及详解:...

java仿servlet生成验证码实例详解

实现原理:使用bufferedimage对象的graphics来进行绘制,然后输出成一张图片进行保存

实现代码及详解:

public class validatecode{

  private static random rand = new random();

  public static void main(string[] args){
    int val1 = rand.nextint(9);
    int val2 = rand.nextint(9);
    int val3 = rand.nextint(9);
    int val4 = rand.nextint(9);
    string val = val1 + " " + val2 + " " + val3 + " " + val4'
    bufferedimage buf = drawimage(val);
    //将最终的图片保存到d://cheng.png下
    imageio.write(buf,"png",new file("d://cheng.png");
  }

  public static bufferedimage drawimage(string code){
    int height = 30;
    int width = 60;
    bufferedimage buf = new bufferedimage(width,height,bufferedimage.type_int_rgb);
    graphics2d gs = buf.creategraphics();
    gs.setbackground(color.black);
    gs.drawrect(0,0,width,height); 

    //绘制随机干扰线
    int total = 100;
    drawrandline(gs,total);

    //绘制验证码
    font font = new font("行楷",font.bold,20);
    gs.setfont(font);
    gs.setcolor(getrandcolor(155,255));
    gs.drawstring(code,5,20);

    return buf;
  }

  public static void drawrandline(graphics2d gs,int total){

    for(int i=0; i<total; i++){
      int x1 = rand.nextint(width);
      int x2 = rand.nextint(width);
      int y1 = rand.nextint(height);
      int y2 = rand.nextint(height);
      //设置随机颜色
      gs.setcolor(getrandcolor(0,155));
      gs.drawline(x1,y1,x2,y2);
    }  
  }

  public static color getrandcolor(int from,int to){

    int r = from + rand.nextint(to-from);
    int g = from + rand.nextint(to-from);
    int b = from + rand.nextint(to-from);
    return new color(r,g,b);  
  }

最终实现效果图

java仿Servlet生成验证码实例详解

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!