0

0

Java生成图形验证码工具类的详细介绍

黄舟

黄舟

发布时间:2017-03-09 10:20:17

|

2066人浏览过

|

来源于php中文网

原创

这篇文章主要介绍了java生成图形验证码工具类,本文思路明确介绍的非常详细,需要的朋友可以参考下

生成验证码效果

ValidateCode.java 验证码生成类

package cn.dsna.util.images; 
import java.awt.Color; 
import java.awt.Font; 
import java.awt.Graphics2D; 
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; 
/** 
 * 验证码生成器 
 * @author dsna 
 * 
 */ 
public class ValidateCode { 
 // 图片的宽度。 
 private int width = 160; 
 // 图片的高度。 
 private int height = 40; 
 // 验证码字符个数 
 private int codeCount = 5; 
 // 验证码干扰线数 
 private int lineCount = 150; 
 // 验证码 
 private String code = null; 
 // 验证码图片Buffer 
 private BufferedImage buffImg=null; 
 private 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 ValidateCode() { 
  this.createCode(); 
 } 
 /** 
  * 
  * @param width 图片宽 
  * @param height 图片高 
  */ 
 public ValidateCode(int width,int height) { 
  this.width=width; 
  this.height=height; 
  this.createCode(); 
 } 
 /** 
  * 
  * @param width 图片宽 
  * @param height 图片高 
  * @param codeCount 字符个数 
  * @param lineCount 干扰线条数 
  */ 
 public ValidateCode(int width,int height,int codeCount,int lineCount) { 
  this.width=width; 
  this.height=height; 
  this.codeCount=codeCount; 
  this.lineCount=lineCount; 
  this.createCode(); 
 } 
 public void createCode() { 
  int x = 0,fontHeight=0,codeY=0; 
  int red = 0, green = 0, blue = 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(); 
  // 生成随机数 
  Random random = new Random(); 
  // 将图像填充为白色 
  g.setColor(Color.WHITE); 
  g.fillRect(0, 0, width, height); 
  // 创建字体 
  ImgFontByte imgFont=new ImgFontByte(); 
  Font font =imgFont.getFont(fontHeight); 
  g.setFont(font); 
  for (int i = 0; i < lineCount; i++) { 
   int xs = random.nextInt(width); 
   int ys = random.nextInt(height); 
   int xe = xs+random.nextInt(width/8); 
   int ye = ys+random.nextInt(height/8); 
   red = random.nextInt(255); 
   green = random.nextInt(255); 
   blue = random.nextInt(255); 
   g.setColor(new Color(red, green, blue)); 
   g.drawLine(xs, ys, xe, ye); 
  } 
  // randomCode记录随机产生的验证码 
  StringBuffer randomCode = new StringBuffer(); 
  // 随机产生codeCount个字符的验证码。 
  for (int i = 0; i < codeCount; i++) { 
   String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]); 
   // 产生随机的颜色值,让输出的每个字符的颜色值都将不同。 
   red = random.nextInt(255); 
   green = random.nextInt(255); 
   blue = random.nextInt(255); 
   g.setColor(new Color(red, green, blue)); 
   g.drawString(strRand, (i + 1) * x, codeY); 
   // 将产生的四个随机数组合在一起。 
   randomCode.append(strRand); 
  } 
  // 将四位数字的验证码保存到Session中。 
  code=randomCode.toString();  
 } 
 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(); 
 } 
 public BufferedImage getBuffImg() { 
  return buffImg; 
 } 
 public String getCode() { 
  return code; 
 } 
}

ImgFontByte.java

立即学习Java免费学习笔记(深入)”;

package cn.dsna.util.images; 
import java.io.ByteArrayInputStream; 
import java.awt.*; 
/** 
 * ttf字体文件 
 * @author dsna 
 * 
 */ 
public class ImgFontByte { 
 public Font getFont(int fontHeight){ 
  try { 
   Font baseFont = Font.createFont(Font.TRUETYPE_FONT, new ByteArrayInputStream(hex2byte(getFontByteStr()))); 
   return baseFont.deriveFont(Font.PLAIN, fontHeight); 
  } catch (Exception e) { 
   return new Font("Arial",Font.PLAIN, fontHeight); 
  } 
 } 
 private byte[] hex2byte(String str) { 
  if (str == null) 
   return null; 
  str = str.trim(); 
  int len = str.length(); 
  if (len == 0 || len % 2 == 1) 
   return null; 
  byte[] b = new byte[len / 2]; 
  try { 
   for (int i = 0; i < str.length(); i += 2) { 
    b[i / 2] = (byte) Integer 
      .decode("0x" + str.substring(i, i + 2)).intValue(); 
   } 
   return b; 
  } catch (Exception e) { 
   return null; 
  } 
 } /** 
 * ttf字体文件的十六进制字符串 
 * @return 
 */ 
 private String getFontByteStr(){ return null; 
  return str;//字符串太长 在附件中找 
} 
}

ValidateCodeServlet.java Servlet调用方法

Spirit Me
Spirit Me

SpiritMe允许用户使用数字化身制作视频,这些化身可以模拟用户的声音和情感

下载

package cn.dsna.util.images; 
import java.io.IOException; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.HttpSession; 
public class ValidateCodeServlet extends HttpServlet { 
 private static final long serialVersionUID = 1L; 
 @Override 
 protected void doGet(HttpServletRequest reqeust, 
   HttpServletResponse response) throws ServletException, IOException { 
  // 设置响应的类型格式为图片格式 
  response.setContentType("image/jpeg"); 
  //禁止图像缓存。 
  response.setHeader("Pragma", "no-cache"); 
  response.setHeader("Cache-Control", "no-cache"); 
  response.setDateHeader("Expires", 0); 
  HttpSession session = reqeust.getSession(); 
  ValidateCode vCode = new ValidateCode(120,40,5,100); 
  session.setAttribute("code", vCode.getCode()); 
  vCode.write(response.getOutputStream()); 
 } 
/** 
 * web.xml 添加servlet 
  
  validateCodeServlet 
  cn.dsna.util.images.ValidateCodeServlet 
   
  
  validateCodeServlet 
  *.images 
  
在地址栏输入XXX/dsna.images 测试 
 */ 
}

 测试类

ValidateCodeTest.java

package cn.dsna.util.images; 
import java.io.IOException; 
import java.util.Date; 
public class ValidateCodeTest { 
 /** 
  * @param args 
  */ 
 public static void main(String[] args) { 
  ValidateCode vCode = new ValidateCode(120,40,5,100); 
  try { 
   String path="D:/t/"+new Date().getTime()+".png"; 
   System.out.println(vCode.getCode()+" >"+path); 
   vCode.write(path); 
  } catch (IOException e) { 
   e.printStackTrace(); 
  } 
 } 
}

web.xml 配置

 
 validateCodeServlet 
 cn.dsna.util.images.ValidateCodeServlet 
  
 
 validateCodeServlet 
 *.images 

相关文章

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
go语言 注释编码
go语言 注释编码

本专题整合了go语言注释、注释规范等等内容,阅读专题下面的文章了解更多详细内容。

2

2026.01.31

go语言 math包
go语言 math包

本专题整合了go语言math包相关内容,阅读专题下面的文章了解更多详细内容。

1

2026.01.31

go语言输入函数
go语言输入函数

本专题整合了go语言输入相关教程内容,阅读专题下面的文章了解更多详细内容。

1

2026.01.31

golang 循环遍历
golang 循环遍历

本专题整合了golang循环遍历相关教程,阅读专题下面的文章了解更多详细内容。

0

2026.01.31

Golang人工智能合集
Golang人工智能合集

本专题整合了Golang人工智能相关内容,阅读专题下面的文章了解更多详细内容。

1

2026.01.31

2026赚钱平台入口大全
2026赚钱平台入口大全

2026年最新赚钱平台入口汇总,涵盖任务众包、内容创作、电商运营、技能变现等多类正规渠道,助你轻松开启副业增收之路。阅读专题下面的文章了解更多详细内容。

76

2026.01.31

高干文在线阅读网站大全
高干文在线阅读网站大全

汇集热门1v1高干文免费阅读资源,涵盖都市言情、京味大院、军旅高干等经典题材,情节紧凑、人物鲜明。阅读专题下面的文章了解更多详细内容。

73

2026.01.31

无需付费的漫画app大全
无需付费的漫画app大全

想找真正免费又无套路的漫画App?本合集精选多款永久免费、资源丰富、无广告干扰的优质漫画应用,涵盖国漫、日漫、韩漫及经典老番,满足各类阅读需求。阅读专题下面的文章了解更多详细内容。

67

2026.01.31

漫画免费在线观看地址大全
漫画免费在线观看地址大全

想找免费又资源丰富的漫画网站?本合集精选2025-2026年热门平台,涵盖国漫、日漫、韩漫等多类型作品,支持高清流畅阅读与离线缓存。阅读专题下面的文章了解更多详细内容。

19

2026.01.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Kotlin 教程
Kotlin 教程

共23课时 | 3.1万人学习

C# 教程
C# 教程

共94课时 | 8.1万人学习

Java 教程
Java 教程

共578课时 | 54.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号