Java实现动态获取图片验证码的示例代码

 更新时间:2019年08月16日 09:57:54   作者:枫止水  
这篇文章主要介绍了Java实现动态获取图片验证码的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

本文介绍了Java实现动态获取图片验证码的示例代码,分享给大家,具体如下:

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Random;
 
 
public class ImgAuthCode {
 
  /**
   * 图片的宽度
   */
  private int width = 330;
  /**
   * 图片的高度
   */
  private int height = 40;
  /**
   * 验证码字符个数
   */
  private int codeCount = 5;
  /**
   * 验证码干扰线数
   */
  private int lineCount = 150;
  /**
   * 图片验证码类型
   */
  private ImgCodeType imgCodeType = DEFAULT_TYPE;
  /**
   * 验证码
   */
  private String code = null;
  /**
   * 验证码图片Buffer
   */
  private BufferedImage buffImg = null;
 
  private static final ImgCodeType DEFAULT_TYPE = ImgCodeType.ENANDNUMBER;
 
  private static char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
      'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
 
  public ImgAuthCode() {
    this.createCode();
  }
 
  /**
   * @param width 图片宽
   * @param height 图片高
   */
  public ImgAuthCode(int width, int height) {
    this.width = width;
    this.height = height;
    this.createCode();
  }
 
  /**
   * @param width   图片宽
   * @param height  图片高
   * @param codeCount 字符个数
   * @param lineCount 干扰线条数
   */
  public ImgAuthCode(int width, int height, int codeCount, int lineCount,ImgCodeType imgCodeType) {
    this.width = width;
    this.height = height;
    this.codeCount = codeCount;
    this.lineCount = lineCount;
    this.imgCodeType = imgCodeType;
    this.createCode();
  }
 
  public void createCode() {
    int x = 0, fontHeight = 0, codeY = 0;
    x = width / (codeCount + 2);// 每个字符的宽度
    fontHeight = height - 2;// 字体的高度
    codeY = height - 4;
 
    // 图像buffer
    buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = buffImg.createGraphics();
    // 将图像填充为白色
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, width, height);
    // 创建字体
//    ImgFontByte imgFont = new ImgFontByte();
//    Font font = imgFont.getFont(fontHeight);
    Font font=new Font("微软雅黑",Font.PLAIN, fontHeight);
    g.setFont(font);
    drawRandomLine(g);
    // randomCode记录随机产生的验证码
    StringBuffer randomCode = new StringBuffer();
    // 随机产生codeCount个字符的验证码。
    for (int i = 0; i < codeCount; i++) {
      String strRand = getRandomStr(imgCodeType);
      // 产生随机的颜色值,让输出的每个字符的颜色值都将不同。
      g.setColor(getRandomColor());
      g.drawString(strRand, (i + 1) * x, codeY);
      // 将产生的四个随机数组合在一起。
      randomCode.append(strRand);
    }
    this.code = randomCode.toString();
  }
 
  private void drawRandomLine(Graphics g){
    //干扰线
    for (int i = 0; i < lineCount; i++) {
      int xs = new Random().nextInt(width);
      int ys = new Random().nextInt(height);
      int xe = xs + new Random().nextInt(width / 8);
      int ye = ys + new Random().nextInt(height / 8);
      g.setColor(getRandomColor());
      g.drawLine(xs, ys, xe, ye);
    }
  }
 
  public Color getRandomColor(){
    int red = 0, green = 0, blue = 0;
    Random random = new Random();
    red = random.nextInt(255);
    green = random.nextInt(255);
    blue = random.nextInt(255);
    return new Color(red,green,blue);
  }
 
  public String getRandomStr(ImgCodeType type) {
    switch (type) {
      case ENANDNUMBER:
        return creatENAndNumberCode();
      case HAN:
        return creatHan();
      case EN:
        return creatENCode();
      case NUMBER:
        return creatNumberCode();
      default:
        return creatENAndNumberCode();
    }
  }
 
  public void write(String path) throws IOException {
    OutputStream sos = new FileOutputStream(path);
    this.write(sos);
  }
 
  public void write(OutputStream sos) throws IOException {
    ImageIO.write(buffImg, "png", sos);
    sos.close();
  }
 
  /**
   * 单个汉字
   *
   * @return
   */
  public static String creatHan() {
    String code = "";
    Random random = new Random();
    //一个汉字两个字节
    byte[] bytes = new byte[2];
    bytes[0] = Integer.valueOf(176 + Math.abs(random.nextInt(39))).byteValue();
    bytes[1] = Integer.valueOf(161 + Math.abs(random.nextInt(93))).byteValue();
    try {
      code = new String(bytes, "GBK");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return code;
  }
 
  /**
   * 英文字母加数字
   *
   * @return
   */
  public static String creatENAndNumberCode() {
    Random random = new Random();
    return String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
  }
 
  /**
   * 英文字母
   * 
   *
   * @return
   */
  public static String creatENCode() {
    StringBuffer code = new StringBuffer();
    Random random = new Random();
    int s = random.nextInt(25) + 65;
    code.append((char) s);
    return code.toString();
  }
 
 
  /**
   * 纯数字验证码
   * 
   *
   * @return
   */
  public static String creatNumberCode() {
    StringBuffer code = new StringBuffer();
    Random random = new Random();
    return code.append(random.nextInt(9) + "").toString();
  }
 
 
  public BufferedImage getBuffImg() {
    return buffImg;
  }
 
  public String getCode() {
    return code;
  }
 
  public void setCode(String code) {
    this.code = code;
  }
 
 
  public static void main(String[] args) {
    String randomChineseChar = creatHan();
    String randomEnChar = creatENCode();
    System.out.println("args = [" + randomChineseChar + "]");
    System.out.println("args = [" + randomEnChar + "]");
  }
}

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

相关文章

  • Java+OpenCV调用摄像头实现拍照功能

    Java+OpenCV调用摄像头实现拍照功能

    随着我们对环境、Mat基本使用越来越熟练、Java Swing也逐步熟悉了起来。本文将通过OpenCV驱动摄像头实现识脸和拍照功能,需要的可以参考一下
    2022-03-03
  • SpringBoot Mail邮件任务详情

    SpringBoot Mail邮件任务详情

    这篇文章主要介绍了SpringBoot Mail邮件任务详情,文章通过spring-boot-starter-mail包展开详细内容,需要的小伙伴可以参考一下
    2022-05-05
  • java采用中文方式显示时间的方法

    java采用中文方式显示时间的方法

    这篇文章主要介绍了java采用中文方式显示时间的方法,实例分析了java时间操作及字符串转换的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07
  • MyBatis中SQL片段复用使用方法详解

    MyBatis中SQL片段复用使用方法详解

    在使用 MyBatis 进行数据库操作时,常常会遇到一些 SQL 语句的部分内容重复出现的情况,比如多个查询语句都涉及相同的字段列表,这时,MyBatis 的 SQL 片段复用功能就派上用场了,接下小编给大家介绍了MyBatis中SQL片段复用使用方法,需要的朋友可以参考下
    2024-12-12
  • 详解如何使用Spring的@FeignClient注解实现通信功能

    详解如何使用Spring的@FeignClient注解实现通信功能

    SpringBoot是一个非常流行的Java框架,它提供了一系列工具来使这种交互无缝且高效,在这些工具中,@FeignClient注解因其易用性和强大的功能而脱颖而出, 在这篇文章中,我们将探讨如何使用Spring的@FeignClient注解进行客户端-服务器通信,需要的朋友可以参考下
    2023-11-11
  • java并发包中CountDownLatch和线程池的使用详解

    java并发包中CountDownLatch和线程池的使用详解

    这篇文章主要介绍了java并发包中CountDownLatch和线程池的使用详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • Java实现简单抽奖功能界面

    Java实现简单抽奖功能界面

    这篇文章主要为大家详细介绍了Java实现简单抽奖功能界面,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-11-11
  • Java继承extends与super关键字详解

    Java继承extends与super关键字详解

    本篇文章给大家详细讲述了Java继承extends与super关键字的相关知识点,需要的朋友们可以参考学习下。
    2018-02-02
  • 实例代码讲解JAVA多线程

    实例代码讲解JAVA多线程

    这篇文章主要介绍讲解JAVA多线程的有关知识,文中示例代码非常详细,供大家参考和学习,感兴趣的朋友可以了解下
    2020-06-06
  • 使用Log4j为项目配置日志输出应用详解以及示例演示的实现分析

    使用Log4j为项目配置日志输出应用详解以及示例演示的实现分析

    本篇文章是对Log4j为项目配置日志输出应用详解以及示例演示的实现进行了分析介绍,需要的朋友参考下
    2013-05-05

最新评论