我们平时开发时经常会遇到需要图片验证码,基础的验证码包括了数字、字母、甚至可能有汉字。下面我给出一个简单的工具类。

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工具类的更多相关文章

  1. java工具类系列 (四.SerializationUtils)

    java工具类系列 (四.SerializationUtils) SerializationUtils该类为序列化工具类,也是lang包下的工具,主要用于序列化操作 import java.io.Se ...

  2. Java工具类——通过配置XML验证Map

    Java工具类--通过配置XML验证Map 背景 在JavaWeb项目中,接收前端过来的参数时通常是使用我们的实体类进行接收的.但是呢,我们不能去决定已经搭建好的框架是怎么样的,在我接触的框架中有一种 ...

  3. 排名前 16 的 Java 工具类

    在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...

  4. 排名前16的Java工具类

    原文:https://www.jianshu.com/p/9e937d178203 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法 ...

  5. 第一章 Java工具类目录

    在这一系列博客中,主要是记录在实际开发中会常用的一些Java工具类,方便后续开发中使用. 以下的目录会随着后边具体工具类的添加而改变. 浮点数精确计算 第二章 Java浮点数精确计算 crc32将任意 ...

  6. java工具类之按对象中某属性排序

    import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang ...

  7. 干货:排名前16的Java工具类

    在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...

  8. Java工具类:给程序增加版权信息

       我们九天鸟的p2p网贷系统,基本算是开发完成了.   现在,想给后端的Java代码,增加版权信息.   手动去copy-paste,太没有技术含量. 于是,写了个Java工具类,给Java源文件 ...

  9. 常用高效 Java 工具类总结

    一.前言 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码 ...

随机推荐

  1. 关于Elixir游戏服设计系列

    写着写着就废球了,感觉空对空,实在没什么意思. 另外很快就要搞新项目,决定新项目就直接上elixir了.目前该做的准备工作已经探索了一些了. 以下的东西是写给同事参考的,感兴趣的可以看看,提建议更好. ...

  2. Go语言备忘录:反射的原理与使用详解

    目录: 预备知识 reflect.Typeof.reflect.ValueOf Value.Type 动态调用 通过反射可以修改原对象 实现类似“泛型”的功能   1.预备知识: Go的变量都是静态类 ...

  3. Python实战之正则表达式RE/re学习笔记及简单练习

    # .,\w,\s,\d,,^,$# *,+,?,{n},{n,},{n,m}# re模块用于对python的正则表达式的操作.## 字符:## . 匹配除换行符以外的任意字符# \w 匹配字母或数字 ...

  4. Druid源码阅读之连接池

    概述 Druid是阿里巴巴开源的一个数据库连接池 源码地址.下面简单分析一下连接池是怎么实现的 怎么开始阅读 如果使用过Druid连接池的都只要在Spring配置中配置jdbc的时候配置Driver是 ...

  5. zoj3710 friends(floyd变形)

    Friends Time Limit: 2 Seconds      Memory Limit: 65536 KB Alice lives in the country where people li ...

  6. 使用keepalived使用主备热备份功能

    图: 配置文件: 主服务器的配置如下: global_defs { router_id NodeA}vrrp_instance VI_1 { state MASTER #设置为主服务器 interfa ...

  7. 【转载】使用CSS将图片转换成黑白(灰色、置灰)

    文章转载自 张鑫旭-鑫空间-鑫生活 http://www.zhangxinxu.com/ 原文链接:http://www.zhangxinxu.com/wordpress/?p=2547原文摘要: . ...

  8. 【Windows 10 应用开发】使用x:Bind标记动态获得计算结果

    UWP 在传统(WPF)的Binding标记上引入了 Bind 标记,Bind 基于编译阶段生成,因而具有较高的性能.但是,你得注意,这个性能上的优化是免去了运行阶段动态绑定的开销,这是不包括数据源的 ...

  9. Java方法使用的有点总结

    方法使用的优点: 1-将解决问题的方法与主函数代码分开,逻辑更清晰,代码可读性更强. 2-若方法出错,则程序可以缩小为只在该方法中查找错误,使代码更容易调试. 3-方法是解决一类问题的抽象,一旦写成功 ...

  10. PHP开发者必须了解的9个魔术方法

    这些'魔术'方法拥有者特殊的名字,以两个下划线开始,表示这些方法在PHP特定事件下将会被触发.这可能听起来有点自动魔法但是它真的很酷的,我们已经看过一个简单的例子在 last post,即我们使用一个 ...