Java代码随机生成图片验证码
- package com.rchm.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;
- /**
- * 验证码生成器
- */
- 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', '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 static String getCode() {
- return code;
- }
- }
在 servlet 中使用该类:
- package com.rchm.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;
- protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
- response.setContentType("image/jpeg");
- response.setHeader("Pragma", "no-cache");
- response.setHeader("Cache-Control", "no-cache");
- response.setDateHeader("Expires", 0);
- ValidateCode vCode = new ValidateCode(100,30,4,100);
- HttpSession session = request.getSession();
- session.removeAttribute("validateCode");
- vCode.write(response.getOutputStream());
- session.setAttribute("validateCode", vCode.getCode());
- vCode.write(response.getOutputStream());
- }
- }
在 web.xml配置Servlet访问路径:
- <servlet>
- <servlet-name>validateCodeServlet</servlet-name>
- <servlet-class>com.rchm.util.images.ValidateCodeServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>validateCodeServlet</servlet-name>
- <url-pattern>code.images</url-pattern>
Java代码随机生成图片验证码的更多相关文章
- python 全栈开发,Day85(Git补充,随机生成图片验证码)
昨日内容回顾 第一部分:django相关 1.django请求生命周期 1. 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端 请求头和请求体中会包含浏览器的动作(action),这 ...
- Django登录(含随机生成图片验证码)注册实例
登录,生成随机图片验证码 一.登录 - 随机生成图片验证码 1.随机生成验证码 Python随机生成图片验证码,需要使用PIL模块,安装方式如下: pip3 install pillow 1)创建图片 ...
- springboot搭建项目,实现Java生成随机图片验证码。
这篇文章主要介绍了如何通过Java如何生成验证码并验证.验证码的作用我想必大家都知道,话不多说开始实施! 首先创建一个springboot项目以下是项目结构,内有utli工具类.存放生成图片验证码方法 ...
- Java生成随机图片验证码
前台html代码 [Java] 纯文本查看 复制代码 ? 01 02 03 04 05 06 07 08 09 10 <div style="margin-top: 50px;&quo ...
- Django---登录(含随机生成图片验证码)、注册示例讲解
登录(验证码).注册功能具体代码 # urls.py from django.contrib import admin from django.urls import path from app01 ...
- java代码发送邮箱验证码与qq邮箱smtp服务
发送邮箱的类封装,在此之前需要一个jar包 javax.mail.jar 下载链接https://github.com/javaee/javamail/releases/download/JAVAM ...
- servletResponse 随机生成图片验证码
/***********************************servlet页面************************************/ package response; ...
- java代码--------随机输出100个随机数,要求每行10个数
总结:不敢爱你么开口 package com.sads; ///实现随机输出100个数字,数字是0到9之间,每行输出10个 public class Wss { public static void ...
- python 随机生成图片验证码背景RGB-浅色或者深色
import random def random_color(is_light = True): return (random.randint(0 ,127) + int(is_light) * 12 ...
随机推荐
- MD5-UTF8-大写加密
private string GetMD5Hash(string str) { string md5Str = ""; byte[] buffer = Encoding.UTF8. ...
- 弹层组件文档 - layui.layer
http://www.layui.com/doc/modules/layer.html
- Hadoop InputFormat详解
InputFormat是MapReduce编程模型包括5个可编程组件之一,其余4个是Mapper.Partitioner.Reducer和OutputFormat. 新版Hadoop InputFor ...
- 【Unity3D】简要分析unity3d中剪不断理还乱的yield
在学习unity3d的时候很容易看到下面这个例子: void Start () { StartCoroutine(Destroy()); } IEnumerator Destroy(){ yield ...
- webservice初识,SOAP1.1版本
客户端与服务端模式,非web端发布 1.1 [Jax-ws第一个例子] 1.1.1 第一步:服务端开发 编写SEI(Service Endpoint Interface),SEI在w ...
- 一般的linux系统默认安装的vim是精简版
一般的linux系统默认安装的vim是精简版(vim-tiny),所以不能配置语法检查等属性或获取在线帮助.需要安装vim-x:x.x.x,vim-common,vim-runtime. :synta ...
- Maven的学习资料收集--(五)使用Maven构建Struts2项目
在前两篇博客中,使用Maven构建了Web项目,在这篇博客中写一下,怎样构建一个简单的Struts2项目. 在准备过程中发现,要使用好Maven,个人觉得要好好利用这两个网站: http://mvnr ...
- git与github的区别
一直纠结于这俩个的区别,今天有时间翻看了一些有关git的详解终于把这个问题搞得清楚了,大概就是下面的意思: Git是一款免费.开源的分布式版本控制系统 Github是用Git做版本控制的代码托管平台
- Vue通过状态为页面切换添加loading、为ajax加载添加loading
以下方法需要引入vuex,另使用了vux的UI框架,ajax添加loading还引入了axios. 一.为页面切换添加loading. loading.js: import Vue from 'vue ...
- pure响应式布局
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...