当前位置: 移动技术网 > IT编程>开发语言>Java > java仿Servlet生成验证码实例详解

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

很很色,河道护坡,美女蛇神

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);  
  }

最终实现效果图

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网