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

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. Array Partition I

    Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1 ...

  2. JavaWeb(二)会话管理之细说cookie与session

    前言 前面花了几篇博客介绍了Servlet,讲的非常的详细.这一篇给大家介绍一下cookie和session. 一.会话概述 1.1.什么是会话? 会话可简单理解为:用户开一个浏览器,点击多个超链接, ...

  3. Theano学习-scan循环

    \(1.Scan\) 通用的一般形式,可用于循环 减少和映射(对维数循环)是特殊的 \(scan\) 对输入序列进行 \(scan\) 操作,每一步都能得到一个输出 \(scan\) 能看到定义函数的 ...

  4. day01:study HTTP协议

    总结: 1.对web客户端和web服务器之间的通讯有了基本原理有了简单理解. 2.对http协议有了相关概念的建立 3.B/S C/S 两种形式 4.搭建tomcat服务器的环境,相关配置(虚拟目录 ...

  5. PowerBI开发 第七篇:数据集和数据刷新

    PowerBI报表是基于数据分析的引擎,数据真正的来源(Data Source)是数据库,文件等数据存储媒介,PowerBI支持的数据源类型多种多样.PowerBI Service(云端)有时不直接访 ...

  6. 消息队列、OSS常用操作封装

    public class MessageQueue { #region Private Properties private const string _accessKeyId = "&qu ...

  7. Sql Server合并多行询数据到一行:使用自连接、FOR XML PATH('')、STUFF或REPLACE函数

    示例表 tb 数据如下 id value ----- 1 aa 1 bb 2 aaa 2 bbb 2 ccc SELECT id, [val] = ( SELECT [value] + ',' FRO ...

  8. 1、Http概述

    1.1 Web客户端和服务器 HTTP 客户端和 HTTP 服务器共同构成了万维网的基本组件,客户端向服务器发送 HTTP 请求, 服务器会在 HTTP 响应中回送所请求的数据. 示意图: 1.2 媒 ...

  9. UWP appButtonBar样式

    UWP 的appButtonBar使用<AppBarButton Icon = "Next" Label = "Next" /> Icon是 Sym ...

  10. day38(增强类的实现)

    定义一个接口 package com.baidu.test; public interface Person { public abstract void eat(); public abstract ...