一、验证码生成类

 package hbi.tech.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random; /**
* 验证码生成器
*
*/
public class SCaptcha {
// 图片的宽度。
private int width = 120;
// 图片的高度。
private int height = 40;
// 验证码字符个数
private int codeCount = 4;
// 验证码干扰线数
private int lineCount = 50;
// 验证码
private String code = null;
// 验证码图片Buffer
private BufferedImage buffImg = null; private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'M', 'N', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };
// 生成随机数
private Random random = new Random(); public SCaptcha() {
this.createCode();
} /**
*
* @param width 图片宽
* @param height 图片高
*/
public SCaptcha(int width, int height) {
this.width = width;
this.height = height;
this.createCode();
} /**
*
* @param width 图片宽
* @param height 图片高
* @param codeCount 字符个数
* @param lineCount 干扰线条数
*/
public SCaptcha(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 codeX = 0;
int fontHeight = 0;
fontHeight = height - 5;// 字体的高度
codeX = width / (codeCount + 3);// 每个字符的宽度 // 图像buffer
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics(); // 将图像填充为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height); // 创建字体
ImgFontByte imgFont = new ImgFontByte();
Font font = imgFont.getFont(fontHeight);
g.setFont(font); StringBuffer randomCode = new StringBuffer();
// 随机产生验证码字符
for (int i = 0; i < codeCount; i++) {
String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
// 设置字体颜色
g.setColor(getRandomColor());
// 设置字体位置
g.drawString(strRand, (i + 1) * codeX, getRandomNumber(height / 2) + 25);
randomCode.append(strRand);
}
code = randomCode.toString();
} /** 获取随机颜色 */
private Color getRandomColor() {
int r = getRandomNumber(255);
int g = getRandomNumber(255);
int b = getRandomNumber(255);
return new Color(r, g, b);
} /** 获取随机数 */
private int getRandomNumber(int number) {
return random.nextInt(number);
} 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;
} /** 字体样式类 */
class ImgFontByte {
public Font getFont(int fontHeight) {
try {
Font baseFont = Font.createFont(Font.HANGING_BASELINE, 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;
}
} // 字体文件的十六进制字符串
private String getFontByteStr() {
//防止报字符串长度过长错误,改为从配置文件读取
return ReadFontByteProperties.getFontByteStr();
}
}
}

二、读取字体文件类

 package hbi.tech.utils;
import java.io.InputStream;
import java.util.Properties;
public class ReadFontByteProperties {
static private String fontByteStr = null;
static {
loads();
}
synchronized static public void loads() {
if (fontByteStr == null) {
InputStream is = ReadFontByteProperties.class.getResourceAsStream("/fontByte.properties");
Properties dbproperties = new Properties();
try {
dbproperties.load(is);
fontByteStr = dbproperties.getProperty("fontByteStr").toString();
} catch (Exception e) {
//System.err.println("不能读取属性文件. " + "请确保fontByte.properties在CLASSPATH指定的路径中");
}
}
}
public static String getFontByteStr() {
if (fontByteStr == null)
loads();
return fontByteStr;
}
}

三、生成验证码接口

    /**
* @author jiaqing.xu@hand-china.com
* @date 2017/8/23
* @description 生成图片验证码
*/
@RequestMapping(value = "/userInfo/verification", method = {RequestMethod.POST, RequestMethod.GET})
@ResponseBody
public void verification(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
// 设置响应的类型格式为图片格式
response.setContentType("image/jpeg");
// 禁止图像缓存。
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
//实例生成验证码对象
SCaptcha instance = new SCaptcha();
//将验证码存入session
session.setAttribute("verification", instance.getCode());
//向页面输出验证码图片
instance.write(response.getOutputStream());
}

将生成的验证码图片存在session中,当用户登录时即可和用户输入的验证码的值进行判断,如果验证相同,则进行后续操作。

java实现图片验证码的更多相关文章

  1. 用Java实现图片验证码功能

    一.什么是图片验证码? 可以参考下面这张图: 我们在一些网站注册的时候,经常需要填写以上图片的信息. 1.图片生成实体类: package com.hexianwei.graphic; import ...

  2. [Java] 识别图片验证码

    现在大多数网站都采用了验证码来防止暴力破解或恶意提交.但验证码真的就很安全吗?真的就不能被机器识别?? 我先讲讲我是怎么实现站外提交留言到一个网站的程序. 这个网站的留言版大致如下: 我一看这种简单的 ...

  3. Java 生产图片验证码

    import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;impor ...

  4. 自己封装的一个java图片验证码

    验证码生成器: package com.lz.Tools; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; ...

  5. java分别通过httpclient和HttpURLConnection获取图片验证码内容

    前面的文章,介绍了如何通过selenium+Tesseract-OCR来识别图片验证码,如果用接口来访问的话,再用selenium就闲的笨重,下面就介绍一下分别通过httpclient和HttpURL ...

  6. 图片验证码的JAVA工具类

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

  7. 用Java制作一个简单的图片验证码

    //Java实现简单验证码功能 package project; import java.awt.Color; import java.awt.Font;import java.awt.Graphic ...

  8. Java如何获取图片验证码保存

    举例网站:https://my.1hai.cn/Login/?url=http://www.1hai.cn/ 一.场景:出于安全性考虑,越来越多的Web平台登录都会增加图形验证码(图片),或者短信验证 ...

  9. 怎样用Java自制优秀的图片验证码?这样!

    Completely Automated Public Turing test to tell Computers and Humans Apart 全自动区分计算机和人类的图灵测试 简称CAPTCH ...

随机推荐

  1. Oracle数据库中心双活之道:ASM vs VPLEX (转)

    双活方案对比:ASM vs V-PLEX 作者:王文杰 Oracle公司 Principle system analyst Oracle高级服务部 Oracle数据库中心的灾备的演变,经历了多年的演变 ...

  2. Hello World 之旅

    本文记录对于下面 `hello.c` 程序在 Linux 上一次运行系统所发生的事情,内容来源于 CSAPP 第一章. #include <stdio.h> int main(int ar ...

  3. 关于AndroidStudio在真机安装的apk闪退(无法打开)的解决方案

    问题描述: 重新安装AndroidStudio之后 1.发现在真机上安装apk时显示的是应用包名. 2.在真机上安装的apk无法打开,一直闪退. 如图: 解决方案: 关闭AndroidStudio的I ...

  4. zstu19一月月赛 duxing201606的原味鸡树

    duxing201606的原味鸡树 题意: 给定一颗有n(n<=1e9)个节点的完全二叉树,1e5次询问,问某个节点有几个子节点. 思路: 自己在月赛上没有思路,问了zfq才知道. 设两个指标, ...

  5. codeforces-214(Div. 2)-C. Dima and Salad+DP恰好背包花费

    codeforces-214(Div. 2)-C. Dima and Salad 题意:有不同的沙拉,对应不同的颜值和卡路里,现在要求取出总颜值尽可能高的沙拉,同时要满足 解法:首先要把除法变成乘法, ...

  6. 计蒜客 ACM训练联盟周赛 第一场 Christina式方格取数 思维

    助手Christina发明了一种方格取数的新玩法:在n*m的方格棋盘里,每个格子里写一个数.两个人轮流给格子染色,直到所有格子都染了色.在所有格子染色完后,计算双方的分数.对于任意两个相邻(即有公共边 ...

  7. ZOJ 3872 Beauty of Array 连续子序列求和

    Edward has an array A with N integers. He defines the beauty of an array as the summation of all dis ...

  8. android日志搜集原理及方案比较

    说明: 本文只讨论Log日志,而不是应用的埋点日志. Android 日志架构 用一张图来了解Android Log的架构: 这里涉及到三个进程: APP进程: 调用Log的接口打日志,最终通过soc ...

  9. Java面试-List中的sort详细解读

    最近看了一些排序相关的文章,因此比较好奇,Java中的排序是如何做的.本片文章介绍的是JDK1.8,List中的sort方法. 先来看看List中的sort是怎么写的: @SuppressWarnin ...

  10. 【Offer】[54] 【二叉搜索树的第k小节点】

    题目描述 思路分析 测试用例 Java代码 代码链接 题目描述 给定一棵二叉搜索树,请找出其中第k小的节点.例如,在下图的二叉搜索树里,按节点数值大小顺序,第三小节点的值是4.  牛客网刷题地址 思 ...