java图形验证码生成工具类

转载自   java图形验证码生成工具类

生成验证码效果

 

 

 

 

ValidateCode.java 验证码生成类

package cn.dsna.util.images;  import java.awt.Color;  
import java.awt.Font;  
import java.awt.Graphics2D;  
import java.awt.image.BufferedImage;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.OutputStream;  
import java.util.Random;  import javax.imageio.ImageIO;  
/** * 验证码生成器 * @author dsna * */  
public class ValidateCode {  // 图片的宽度。  private int width = 160;  // 图片的高度。  private int height = 40;  // 验证码字符个数  private int codeCount = 5;  // 验证码干扰线数  private int lineCount = 150;  // 验证码  private String code = null;  // 验证码图片Buffer  private BufferedImage buffImg=null;  private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',  'K', 'L', 'M', 'N',  'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',  'X', 'Y', 'Z',  '1', '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 +2);//每个字符的宽度  fontHeight = height - 2;//字体的高度  codeY = height - 4;  // 图像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) 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;  }  
}  

ImgFontByte.java

package cn.dsna.util.images;  
import java.io.ByteArrayInputStream;  
import java.awt.*;  
/** * ttf字体文件 * @author dsna * */  
public class ImgFontByte {  public Font getFont(int fontHeight){  try {  Font baseFont = Font.createFont(Font.TRUETYPE_FONT, 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;  }  } /** * ttf字体文件的十六进制字符串 * @return */  private String getFontByteStr(){ return null;  return str;//字符串太长 在附件中找  }  
}  

 ValidateCodeServlet.java Servlet调用方法 

package cn.dsna.util.images;  import java.io.IOException;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.HttpSession;  public class ValidateCodeServlet extends HttpServlet {  private static final long serialVersionUID = 1L;  @Override  protected void doGet(HttpServletRequest reqeust,  HttpServletResponse response) throws ServletException, IOException {  // 设置响应的类型格式为图片格式  response.setContentType("image/jpeg");  //禁止图像缓存。  response.setHeader("Pragma", "no-cache");  response.setHeader("Cache-Control", "no-cache");  response.setDateHeader("Expires", 0);  HttpSession session = reqeust.getSession();  ValidateCode vCode = new ValidateCode(120,40,5,100);  session.setAttribute("code", vCode.getCode());  vCode.write(response.getOutputStream());  }  
/** * web.xml 添加servlet <servlet> <servlet-name>validateCodeServlet</servlet-name> <servlet-class>cn.dsna.util.images.ValidateCodeServlet</servlet-class> </servlet>     <servlet-mapping> <servlet-name>validateCodeServlet</servlet-name> <url-pattern>*.images</url-pattern> </servlet-mapping> 在地址栏输入XXX/dsna.images 测试 */  }  
测试类

ValidateCodeTest.java

package cn.dsna.util.images;  import java.io.IOException;  
import java.util.Date;  public class ValidateCodeTest {  /** * @param args */  public static void main(String[] args) {  ValidateCode vCode = new ValidateCode(120,40,5,100);  try {  String path="D:/t/"+new Date().getTime()+".png";  System.out.println(vCode.getCode()+" >"+path);  vCode.write(path);  } catch (IOException e) {  e.printStackTrace();  }  }  }  

web.xml 配置

<servlet>  <servlet-name>validateCodeServlet</servlet-name>  <servlet-class>cn.dsna.util.images.ValidateCodeServlet</servlet-class>  
</servlet>      
<servlet-mapping>  <servlet-name>validateCodeServlet</servlet-name>  <url-pattern>*.images</url-pattern>  
</servlet-mapping> 
  • dsnaValidateCode.jar (30.4 KB)
  • dsnaValidateCode_src.rar (27.5 KB)


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/328741.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

.NET Core中的认证管理解析

0x00 问题来源 在新建.NET Core的Web项目时选择“使用个人用户账户”就可以创建一个带有用户和权限管理的项目&#xff0c;已经准备好了用户注册、登录等很多页面&#xff0c;也可以使用AuthorizeAttribute进行各种权限管理&#xff0c;看起来似乎十分方便。不过生成的代码都替…

散列算法,Remal使用散列算法

一、散列算法 散列算法让其保证不可逆&#xff0c;安全。这里举一个例子sh1的摘要算法。上代码 /*** 散列算法* author Administrator*/ public class HashRsaUtil {/*** 加密方式*/public static final String SHA1"SHA-1";/*** 加密次数*/public static final In…

简化得最没道理的6个汉字,让人大跌眼镜

文章来源于网络&#xff0c;侵删&#xff01;&#xff01;&#xff01; 1、“進”被简化为“进”&#xff0c;“進”字是让人“越走越佳”。 简化字却把它改成了“进”字&#xff0c;让你越走越走到“井”里去了&#xff0c;井底之蛙自生自灭。 2、“廠”被简化为“厂”字&…

c++

#include <iostream> #include<cmath> using namespace std; int main() { int x; double a; double b; while(cin >> x ){//注意while处理多个case for(int i 0 ;i < x ; i ){ cin>>a; …

在docker中运行ASP.NET Core Web API应用程序

本文是一篇指导快速演练的文章&#xff0c;将介绍在docker中运行一个ASP.NET Core Web API应用程序的基本步骤&#xff0c;在介绍的过程中&#xff0c;也会对docker的使用进行一些简单的描述。对于.NET Core以及docker的基本概念&#xff0c;网上已经有很多文章对其进行介绍了&…

谈谈 Java 的克隆

转载自 谈谈 Java 的克隆为什么要克隆对象 做开发很少用到克隆的。我能想得到的是用于调用方法时作为参数传递&#xff0c;为了保证方法调用前后对象的内部结构不被破坏&#xff0c;可以克隆一个对象作为参数传递。 使类具有克隆能力 有人可能注意到 Object 类中有一个 native…

android启调支付宝

网上找了一个可以起吊支付宝的appdemo &#xff0c;它集成了服务器端&#xff0c;我先将其分离为app和服务器端&#xff0c;保证app在接收参数后可以启调支付宝 &#xff08;保证app这边是正确的 不然出错都不知道是服务器出错还是app出错&#xff09;&#xff0c;在 找网上资…

shiro-身份授权流程、案例

一、身份授权流程 首先调用Subject.isPermitted/hasRole接口&#xff0c;委托给SecurityManager.SecurityManager接着会委托给内部组件Authorizer.Authorizer再将其请求委托给我们的Realm去做&#xff0c;Realm才是真正干活的.realm将用户请求的参数封装成权限对象&#xff0c…

对Java的URL类支持的协议进行扩展的方法

转载自 对Java的URL类支持的协议进行扩展的方法JAVA默认提供了对file,ftp,gopher,http,https,jar,mailto,netdoc协议的支持。当我们要利用这些协议来创建应用时&#xff0c;主要会涉及到如下几个类&#xff1a;java.net.URL、java.net.URLConnection、InputStream。URL类默认…

在.Net项目中使用Redis作为缓存服务

最近由于项目需要&#xff0c;在系统缓存服务部分上了redis&#xff0c;终于有机会在实际开发中玩一下&#xff0c;之前都是自己随便看看写写&#xff0c;很零碎也没沉淀下来什么&#xff0c;这次算是一个系统学习和实践过程的总结。 和Redis有关的基础知识 Redis是一个开源的分…

中国的程序员培训是不是有问题?

内容来源于&#xff0c;看最下面的出处&#xff0c;侵删 中国技术开放日的出海团对日本进行了为期一周的访问。笔者随行了头两天&#xff0c;参加Slush Asia大会&#xff0c;并访问了Gungho和Deloitte两家企业。虽然已经在日本生活了四年&#xff0c;但这样的体验却甚少&#x…

后台回调支付宝

https://blog.csdn.net/u012552275/article/details/78320051 网上找了一个可以起吊支付宝的appdemo &#xff0c;它集成了服务器端&#xff0c;我先将其分离为app和服务器端&#xff0c;保证app在接收参数后可以启调支付宝 &#xff08;保证app这边是正确的 不然出错都不知道…

解决高版本SpringBoot整合swagger时启动报错:Failed to start bean ‘documentationPluginsBootstrapper‘ 问题

一、控制台的报错信息 2021-12-29 15:15:04 [main] ERROR org.springframework.boot.SpringApplication - Application run failed org.springframework.context.ApplicationContextException: Failed to start bean documentationPluginsBootstrapper; nested exception is j…

java图片格式转化(例如jpg格式转化png)

转载自 java图片格式转化&#xff08;例如jpg格式转化png&#xff09; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Scanner;import javax.imageio.*; public class FormatConversion {public static final Str…

微软开源PowerShell并支持Linux

建议在Wifi 环境下观看视频 class"video_iframe" data-vidtype"1" style" z-index:1; " height"375" width"500" frameborder"0" data-src"https://v.qq.com/iframe/preview.html?vidv0322g7kd3f&width…

招银网络科技笔试

记录一下 招银网络笔试 2017年09月11日 14:32:53 阅读数&#xff1a;2450 Part1. 30道单选 涉及Java&#xff0c;C&#xff0c;多线程&#xff0c;算法&#xff0c;数据结构&#xff0c;CPU&#xff0c;NP问题&#xff0c;SQL语句&#xff0c;IP地址转换&#xff0c;行测。…

mybatisGenerator逆向工程

一、在pom文件中导入依赖和generator插件 <dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><dependency&…

2016最佳温情小说:雨还在下....

作者 | 李德霞 来源 | 小小说选刊 哗&#xff0c;一道闪电&#xff1b;轰&#xff0c;一个响雷。 暴雨倾盆&#xff0c;天地间浑沌一片…… 老大扑腾腾坐起来&#xff0c;心也跟着扑腾腾地跳。老大拉亮灯&#xff0c;推推身边的媳妇。媳妇一骨碌爬起来&#xff0c;咋&#xf…

java 中 image 和 byte[] 相互转换

转载自 java 中 image 和 byte[] 相互转换只需要一个存储了图片信息的二进制串&#xff08;byte[]&#xff09; 然后&#xff0c;这样&#xff1a; InputStream buffin new ByteArrayInputStream(/*二进制串*/, /*起始位置*/,/*二进制串长度*/)); BufferedImage img ImageIO…

招银网络

记录一下 招银网络笔试 2017年09月11日 14:32:53 阅读数&#xff1a;2451 Part1. 30道单选 涉及Java&#xff0c;C&#xff0c;多线程&#xff0c;算法&#xff0c;数据结构&#xff0c;CPU&#xff0c;NP问题&#xff0c;SQL语句&#xff0c;IP地址转换&#xff0c;行测。…