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

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. Java比较器

    导语 本节内容,比较器Comparable是核心内容. 主要内容 重新认识Arrays类 两种比较器的使用 具体内容 Arrays类 在之前一直使用的"java.util.Arrays.so ...

  2. iOS10适配相关

    2016年9月7日,苹果发布iOS 10.2016年9月14日,全新的操作系统iOS 10将正式上线. 作为开发者,如何适配iOS10呢? 1.Notification(通知) 自从Notificat ...

  3. Windows 10新功能

    Windows 10 中面向开发人员的新增功能 Windows 10 及新增的开发人员工具将提供新通用 Windows 平台支持的工具.功能和体验.在 Windows 10 上安装完工具和 SDK后, ...

  4. Java常用类(一)String类详解

    前言 在我们开发中经常会用到很多的常用的工具类,这里做一个总结.他们有很多的方法都是我们经常要用到的.所以我们一定要把它好好的掌握起来! 一.String简介 1.1.String(字符串常量)概述 ...

  5. LINUX 笔记-DU 和 DF

    du(disk usage)搜索文件统计文件大小 1.显示指定文件所占空间 du file1 file2 2.显示指定目录占的空间 du dir 3.只显示总和大小 du -s 4.以方便格式显示 d ...

  6. C#,COM口,接收,发送数据

    这里写一种,COM口的数据接收,发送方法. 1.COMHelper类 /// <summary>初始化串行端口</summary> private SerialPort _se ...

  7. Time模块和datetime模块

    Time模块和datetime模块 一. 调用 import time       #调用time模块 二.使用方法 1.time.time 拿到时间戳.以Linux诞生年份1970年开始计算到程序执 ...

  8. 自学Java HashMap源码

    自学Java HashMap源码 参考:http://zhangshixi.iteye.com/blog/672697 HashMap概述 HashMap是基于哈希表的Map接口的非同步实现.此实现提 ...

  9. LeetCode 63. Unique Path II(所有不同路径之二)

    Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How m ...

  10. eclipse查看类源码出现failed to create the part's controls的解决方法

    刚装好eclipse和Tomcat ,在看准备使用的一个开源框架jeesite,可是在查看源代码的时候出现这个问题