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

使用java生成字母验证码

程序员文章站 2024-03-09 09:30:17
本文实例为大家分享了java生成字母验证码的具体代码,供大家参考,具体内容如下 import java.awt.basicstroke; import ja...

本文实例为大家分享了java生成字母验证码的具体代码,供大家参考,具体内容如下

import java.awt.basicstroke;
import java.awt.color;
import java.awt.font;
import java.awt.graphics2d;
import java.awt.image.bufferedimage;
import java.io.ioexception;
import java.io.outputstream;
import java.util.random;

import javax.imageio.imageio;


public class verifycode {
  //图片宽高
  private int w=70;
  private int h=35;
  private random r=new random();
  private string[] fontnames={"宋体","华文楷体","黑体","微软雅黑","楷体_gb2312"};
  private string codes="234567890qwertyuipasdfghjkzxcvbnmqwertyuipasdfghjkzxcvbnm";
  private color bgcolor=new color(255,255,255);
  private string text;
  //生成随机颜色
  private color randomcolor(){
    int red=r.nextint(150);
    int green=r.nextint(150);
    int blue=r.nextint(150);
    return new color(red, green, blue);
    }
  //生成随机字体
  private font randomfont(){
    int index=r.nextint(fontnames.length);
    string fontname=fontnames[index];
    int style=r.nextint(4);//0 无 1 粗体 2 斜体 3 粗+斜
    int size=r.nextint(5)+24; //生成随机字号 24~28
    return new font(fontname, style, size);
  }
  //干扰线
  private void drowline(bufferedimage image){
    //生成4条干扰线
    int num=4;
    graphics2d bi=(graphics2d) image.getgraphics();
    for (int i = 0; i < num; i++) {
      int x1=r.nextint(w);
      int x2=r.nextint(w);
      int y1=r.nextint(h);
      int y2=r.nextint(h);
      bi.setstroke(new basicstroke(1.5f));
      bi.setcolor(color.blue);//干扰线色
      bi.drawline(x1,y1,x2,y2);
    }
  }
  //随机生成一个字符
  private char randomchar(){
    int index=r.nextint(codes.length());
    return codes.charat(index);
  }
  //图片缓冲区
  private bufferedimage createimage(){
    bufferedimage image=new bufferedimage(w, h, bufferedimage.type_int_bgr);
    graphics2d bi=(graphics2d) image.getgraphics();
    bi.setcolor(this.bgcolor);
    bi.fillrect(0, 0, w, h);
    return image;
  }
  //生成图片
  public bufferedimage getimage(){
    bufferedimage image=createimage();
    graphics2d bi=(graphics2d) image.getgraphics();
    stringbuilder sb=new stringbuilder();
    for (int i = 0; i <4; i++) {
      string string=randomchar()+"";
      sb.append(string);
      //每个字符占图片1/4宽
      float x=i*1.0f*w/4;
      //随机字体格式
      bi.setfont(randomfont());
      bi.setcolor(randomcolor());
      //把字写在图片适当处(h-6指图片距底部6个高度)
      bi.drawstring(string, x, h-6);
    }
    this.text=sb.tostring();
    drowline(image);
    return image;
  }
  //返回得到的字体
  public string gettext(){
    return text;
  }
  //把图片写入指定位置
  public static void output(bufferedimage image,outputstream out){
    try {
      imageio.write(image, "jpg", out);
    } catch (ioexception e) {
      e.printstacktrace();
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。