图片验证码的JAVA工具类
我们平时开发时经常会遇到需要图片验证码,基础的验证码包括了数字、字母、甚至可能有汉字。下面我给出一个简单的工具类。
package com..ankang.tony.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Random;
import javax.imageio.ImageIO;
/**
* 验证码生成器
*/
public class ValidateCode {
// 图片的宽度。
private int width = 160;
// 图片的高度。
private int height = 40;
// 验证码字符个数
private int codeCount = 5;
// 验证码干扰线数
private int lineCount = 150;
// 验证码
private static String code = null;
// 验证码图片Buffer
private BufferedImage buffImg = null;
private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '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 + 1);// 每个字符的宽度
fontHeight = height - 2;// 字体的高度
codeY = height - 3;
// 图像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,String fileName) throws IOException {
File folder = new File(path);
if(!folder.exists()){
folder.mkdirs();
}
OutputStream sos = new FileOutputStream(path+fileName);
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;
}
public static void main(String[] args) {
ValidateCode vCode = new ValidateCode(120,40,5,50);
try {
String path="D:\\report\\image\\code\\";
System.out.println(vCode.getCode()+" >"+path);
vCode.write(path,new Date().getTime()+".png");
} catch (IOException e) {
e.printStackTrace();
}
}
}
下面这个类主要是用作字体的设置,大家也可以直接拿过来用。
package com.ankang.tony.util;
import java.awt.Font;
import java.io.ByteArrayInputStream;
public class ImgFontByte {
public Font getFont(int fontHeight){
try {
Font baseFont = Font.createFont(Font.ITALIC, new ByteArrayInputStream(hex2byte(getFontByteStr())));
return baseFont.deriveFont(Font.PLAIN, fontHeight);
} catch (Exception e) {
return new Font("Consola",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;
}
}
图片验证码的JAVA工具类的更多相关文章
- java工具类系列 (四.SerializationUtils)
java工具类系列 (四.SerializationUtils) SerializationUtils该类为序列化工具类,也是lang包下的工具,主要用于序列化操作 import java.io.Se ...
- Java工具类——通过配置XML验证Map
Java工具类--通过配置XML验证Map 背景 在JavaWeb项目中,接收前端过来的参数时通常是使用我们的实体类进行接收的.但是呢,我们不能去决定已经搭建好的框架是怎么样的,在我接触的框架中有一种 ...
- 排名前 16 的 Java 工具类
在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...
- 排名前16的Java工具类
原文:https://www.jianshu.com/p/9e937d178203 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法 ...
- 第一章 Java工具类目录
在这一系列博客中,主要是记录在实际开发中会常用的一些Java工具类,方便后续开发中使用. 以下的目录会随着后边具体工具类的添加而改变. 浮点数精确计算 第二章 Java浮点数精确计算 crc32将任意 ...
- java工具类之按对象中某属性排序
import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang ...
- 干货:排名前16的Java工具类
在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...
- Java工具类:给程序增加版权信息
我们九天鸟的p2p网贷系统,基本算是开发完成了. 现在,想给后端的Java代码,增加版权信息. 手动去copy-paste,太没有技术含量. 于是,写了个Java工具类,给Java源文件 ...
- 常用高效 Java 工具类总结
一.前言 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码 ...
随机推荐
- 从DDD开始说起
前言 从13年接触DDD之后开始做应用架构已经整整四个年头. 四年里关于DDD的感触良多,慢慢有了一些心得. 关于DDD的介绍已经有很多的文章和书籍,这里我推荐三本最重要的书籍. <领域驱动设计 ...
- mybatis一对一嵌套查询
要求:查询一个员工的时候,把他对应的部门也查询出来 实现(其他配置这里不作说明,框架基于spring_springMVC_mybatis_oracle): 如有不对或不适的地方,请多多指教. 1.新建 ...
- HDU 5934 强联通分量
Bomb Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submis ...
- Layer弹层组件 二次扩展,项目中直接使用。
/************************ Layer扩展 ****************************/ /* * Layer弹出Alert提示框 * @param messag ...
- Pyhton编程(二)之变量、用户输入及条件语句
一:变量 变量定义的规则 1)只能由数字.字母.下划线组成(不能以数字开头) 2)不能使用关键字作为变量名 ['and', 'as', 'assert', 'break', 'class', 'con ...
- Java集合源码分析(一)ArrayList
前言 在前面的学习集合中只是介绍了集合的相关用法,我们想要更深入的去了解集合那就要通过我们去分析它的源码来了解它.希望对集合有一个更进一步的理解! 既然是看源码那我们要怎么看一个类的源码呢?这里我推荐 ...
- (@WhiteTaken)设计模式学习——享元模式
继续学习享元模式... 乍一看到享元的名字,一头雾水,学习了以后才觉得,这个名字确实比较适合这个模式. 享元,即共享对象的意思. 举个例子,如果制作一个五子棋的游戏,如果每次落子都实例化一个对象的话, ...
- linux 下的文件目录操作之遍历目录
通过递归调用读取目录和文件信息去遍历整个目录: 示例代码: #include <unistd.h> #include <stdio.h> #include <dirent ...
- linux 投影仪
注:文章转自http://goo.gl/aI9Ycd如果侵权,请原作者留言,立即删除 之前在 R219 做 C++ 演講的時候,發現 Ubuntu 沒有辦法使用 VGA 輸出,臨時改用 Windows ...
- js中的undefined 和null
undefined是基本数据类型 表示未定义 缺少的意思 null是引用数据类型 是对象 表示空对象 undefined是从null派生出来的 所以undefined==null true Ja ...