图片验证码生成

时间:2023-02-09 22:05:51

生成的验证码:图片验证码生成


/**

* 以图片的形式生成验证码并保存至本地文件中

**/

public class demo {

  public static String[] character = {"A","B","C","D","E","F","G","H"};
  public static int width = 90;
  public static int height = 30;
  public static int CHAR_WIDTH = 16;
  public static int CHAR_HEIGHT = 20;
  
  public static void main(String[] args) throws IOException{   
    BufferedImage buffImage = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
    Graphics gd = buffImage.getGraphics();
    gd.setColor(Color.CYAN);
    gd.fillRect(0, 0, width, height);
    Font font = new Font("宋体", Font.BOLD, 18);
    gd.setFont(font);
    
    gd.setColor(Color.BLACK);
    Random random = new Random();
    
    /* 随机生成多条扰乱视线的线条 */
    for(int i =0;i<10;i++){
      int x = random.nextInt(width);
      int y = random.nextInt(height);
      int x1 = random.nextInt(width);
      int y1 = random.nextInt(height);
      gd.drawLine(x, y, x1, y1);
    }


    StringBuffer buff = new StringBuffer();
    
    for(int i =0 ; i<5;i++){
      if(random.nextBoolean()){
        int num = random.nextInt(10);
        buff.append(String.valueOf(num));
        setRGB(String.valueOf(num),random, gd,i);
       
      }else{
        String tm = character[random.nextInt(character.length)];
        buff.append(tm);
        if(random.nextBoolean()){
          setRGB(tm,random,gd,i);
        }else{
          setRGB(tm.toLowerCase(),random, gd,i);
        }
      }
    }
/**  查找自己系统可查看的图片格式   **/
//    String[] names = ImageIO.getWriterFormatNames();
//    for(int i =0;i<names.length ;i++){
//      System.out.println(names[i]);
//    }
    System.out.println(buff);
    ImageIO.write(buffImage,"jpeg" , new File("H:/temp.jpeg"));
    
  }


  /** 在写字体前,修改画笔的颜色 **/
  public static void setRGB(String str,Random random,Graphics g,int i ){
    int red = random.nextInt(256);
    int green = random.nextInt(256);
    int blue = random.nextInt(256);

    g.setColor(new Color(red, green, blue));

  /** 位置控制 **/

    g.drawString(str, CHAR_WIDTH*i+4, CHAR_HEIGHT);
  }
}