当前位置: 移动技术网 > IT编程>开发语言>Java > java生成图片验证码示例代码

java生成图片验证码示例代码

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

 本文实例为大家分享了java图片验证码具体实现代码,供大家参考,具体内容如下

import java.awt.color;
import java.awt.font;
import java.awt.graphics;
import java.awt.image.bufferedimage;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.outputstream;
import java.util.random;
import javax.imageio.imageio;
/*
 * 步骤:
 * 1.画框
 * 2.画背景
 * 3.画字符
 * 4.画干扰线
 */
public final class imageutil {
   
  // 验证码字符集
  private static final char[] chars = { 
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 
    'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
  // 字符数量
  private static final int size = 4;
  // 干扰线数量
  private static final int lines = 5;
  // 宽度
  private static final int width = 80;
  // 高度
  private static final int height = 40;
  // 字体大小
  private static final int font_size = 30;
 
  /**
   * 生成随机验证码及图片
   * object[0]验证码字符串string
   * object[1]验证码图片  bufferedimage
   */
  public static object[] createimage() {
    stringbuffer sb = new stringbuffer();
    // 1.创建空白图片
    bufferedimage image = new bufferedimage(
      width, height, bufferedimage.type_int_rgb);
    // 2.获取图片画笔
    graphics graphic = image.getgraphics();
    // 3.设置画笔颜色
    graphic.setcolor(color.light_gray);
    // 4.绘制矩形背景
    graphic.fillrect(0, 0, width, height);
    // 5.画随机字符
    random ran = new random();
    for (int i = 0; i <size; i++) {
      // 取随机字符索引
      int n = ran.nextint(chars.length);
      // 设置随机颜色
      graphic.setcolor(getrandomcolor());
      // 设置字体大小
      graphic.setfont(new font(
        null, font.bold + font.italic, font_size));
      // 画字符
      graphic.drawstring(
        chars[n] + "", i * width / size, height / 2);
      // 记录字符
      sb.append(chars[n]);
    }
    // 6.画干扰线
    for (int i = 0; i < lines; i++) {
      // 设置随机颜色
      graphic.setcolor(getrandomcolor());
      // 随机画线
      graphic.drawline(ran.nextint(width), ran.nextint(height),
          ran.nextint(width), ran.nextint(height));
    }
    // 7.返回验证码和图片
    return new object[]{sb.tostring(), image};
  }
 
  /**
   * 随机取色
   */
  public static color getrandomcolor() {
    random ran = new random();
    color color = new color(ran.nextint(256), 
        ran.nextint(256), ran.nextint(256));
    return color;
  }
   
  public static void main(string[] args) throws ioexception {
    object[] objs = createimage();
    bufferedimage image = (bufferedimage) objs[1];
    //图片格式可以自定义,java对png图片显示更清楚,输出路径可自定义
    outputstream os = new fileoutputstream("d:/x.png");
    //注意图片格式与创建格式匹配
    imageio.write(image, "png", os);
    os.close();
  }
 
}

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网