栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 生成图片验证码3种方法(字母、加减乘除、中文)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 生成图片验证码3种方法(字母、加减乘除、中文)

第一种方法 全是字母和数字组成 

package com.myFirstSpring.util;
 
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
 
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 

public class ValidateCodeUtils extends HttpServlet {
 
 private static final long serialVersionUID = -1409007752285164213L;
 private static int width = 75;
 private static int height = 35;
 // private static char[] ch =
 // "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789".toCharArray();
 private static char[] ch = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
 
 public void doGet(HttpServletRequest request, HttpServletResponse response)
 
 throws ServletException, IOException {
 
 this.doPost(request, response);
 
 }
 
 // 生成数字和字母的验证码
 public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
 processRequest(request, response);
 }
 
 protected void processRequest(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);
 // 在内存中创建图象
 BufferedImage image = new BufferedImage(width, height,
  BufferedImage.TYPE_INT_RGB);
 
 // 获取图形上下文
 Graphics g = image.getGraphics();
 
 // 生成随机类
 Random random = new Random();
 
 // 设定背景色
 g.setColor(getRandColor(200, 250));
 g.fillRect(0, 0, width, height);
 
 // 设定字体
 g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
 
 // 画边框
 // g.setColor(new Color());
 // g.drawRect(0,0,width-1,height-1);
 
 // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
 g.setColor(getRandColor(160, 200));
 for (int i = 0; i < 155; i++) {
  int x = random.nextInt(width);
  int y = random.nextInt(height);
  int xl = random.nextInt(12);
  int yl = random.nextInt(12);
  g.drawLine(x, y, x + xl, y + yl);
 }
 
 // 取随机产生的认证码(4位数字)
 StringBuffer sb = new StringBuffer();
 int index, len = ch.length;
 for (int i = 0; i < 4; i++) {
  index = random.nextInt(len);
  g.setColor(new Color(random.nextInt(88), random.nextInt(188),
   random.nextInt(255)));
  g.setFont(new Font("Arial", Font.ITALIC, 28));// 输出的字体和大小
  g.drawString("" + ch[index], (i * 15) + 6, 26);// 写什么数字,在图片的什么位置画
  sb.append(ch[index]);
 }
 // 将认证码存入SESSION
 request.getSession().setAttribute("piccode", sb.toString());
 request.getSession().setAttribute(request.getSession().getId(), sb.toString());
 
 // 图象生效
 g.dispose();
 ServletOutputStream responseOutputStream = response.getOutputStream();
 // 输出图象到页面
 ImageIO.write(image, "JPEG", responseOutputStream);
 
 // 以下关闭输入流!
 responseOutputStream.flush();
 responseOutputStream.close();
  
 }
 
 protected void ValidateCode(HttpServletRequest request,
  HttpServletResponse response) throws ServletException, IOException {
 // 在内存中创建图象
 BufferedImage img = new BufferedImage(width, height,
  BufferedImage.TYPE_INT_RGB);
 // 得到该图片的绘图对象
 Graphics g = img.getGraphics();
 
 Random r = new Random();
 Color c = new Color(200, 150, 255);
 g.setColor(c);
 
 // 填充整个图片的颜色
 g.fillRect(0, 0, width, height);
 
 // 向图片中输出数字和字母
 StringBuffer sb = new StringBuffer();
 int index, len = ch.length;
 for (int i = 0; i < 4; i++) {
  index = r.nextInt(len);
  g
   .setColor(new Color(r.nextInt(88), r.nextInt(188), r
    .nextInt(255)));
  g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));// 输出的字体和大小
  g.drawString("" + ch[index], (i * 15) + 6, 18);// 写什么数字,在图片的什么位置画
  sb.append(ch[index]);
 }
 
 request.getSession().setAttribute("piccode", sb.toString());
 ServletOutputStream responseOutputStream = response.getOutputStream();
 ImageIO.write(img, "JPG", responseOutputStream);
 responseOutputStream.flush();
 responseOutputStream.close();
 }
 
 Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
 Random random = new Random();
 if (fc > 255)
  fc = 255;
 if (bc > 255)
  bc = 255;
 int r = fc + random.nextInt(bc - fc);
 int g = fc + random.nextInt(bc - fc);
 int b = fc + random.nextInt(bc - fc);
 return new Color(r, g, b);
 }
 
 
 public static String getPath(Class name) {
 String strResult = null;
 if (System.getProperty("os.name").toLowerCase().indexOf("window") > -1) {
  strResult = name.getResource("/").toString().replace("file:/", "")
   .replace("%20", " ");
 } else {
  strResult = name.getResource("/").toString().replace("file:", "")
   .replace("%20", " ");
 }
 return strResult;
 }
}

第二种 中文字符 

package com.myFirstSpring.util;
 
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
 
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 

public class ValidateCodeUtils_zh extends HttpServlet {
  
 private static final long serialVersionUID = 6699312412706395069L;
 public static final int WIDTH = 120;
  public static final int HEIGHT = 30;
 
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    this.doPost(request, response);
  }
 
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    // 创建缓存
    BufferedImage bi = new BufferedImage(WIDTH, HEIGHT,
 BufferedImage.TYPE_INT_RGB);
    // 获得画布
    Graphics g = bi.getGraphics();
 
    // 设置背影色
    setBackGround(g);
    // 设置边框
    setBorder(g);
    // 画干扰线
    drawRandomLine(g);
    // 写随机数
    String random = drawRandomNum((Graphics2D) g);
    // 将随机汉字存在session中
    request.getSession().setAttribute("piccode", random);
    // 将图形写给浏览器
    response.setContentType("image/jpeg");
    // 发头控制浏览器不要缓存
    response.setDateHeader("expries", -1);
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    // 将图片写给浏览器
    ImageIO.write(bi, "jpg", response.getOutputStream());
  }
 
  
  private void setBackGround(Graphics g) {
    // 设置颜色
    g.setColor(Color.WHITE);
    // 填充区域
    g.fillRect(0, 0, WIDTH, HEIGHT);
 
  }
 
  
  private void setBorder(Graphics g) {
    // 设置边框颜色
    g.setColor(Color.BLUE);
    // 边框区域
    g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
  }
 
  
  private void drawRandomLine(Graphics g) {
    // 设置颜色
    g.setColor(Color.GREEN);
    // 设置线条个数并画线
    for (int i = 0; i < 5; i++) {
      int x1 = new Random().nextInt(WIDTH);
      int y1 = new Random().nextInt(HEIGHT);
      int x2 = new Random().nextInt(WIDTH);
      int y2 = new Random().nextInt(HEIGHT);
      g.drawLine(x1, y1, x2, y2);
    }
 
  }
 
  
  private String drawRandomNum(Graphics2D g) {
    StringBuffer sb = new StringBuffer();
    // 设置颜色
    g.setColor(Color.RED);
    // 设置字体
    g.setFont(new Font("宋体", Font.BOLD, 20));
    // 准备常用汉字集
    String base = "u7684u4e00u4e86u662fu6211u4e0du5728u4ebau4eecu6709u6765u4ed6u8fd9u4e0au7740u4e2au5730u5230u5927u91ccu8bf4u5c31u53bbu5b50u5f97u4e5fu548cu90a3u8981u4e0bu770bu5929u65f6u8fc7u51fau5c0fu4e48u8d77u4f60u90fdu628au597du8fd8u591au6ca1u4e3au53c8u53efu5bb6u5b66u53eau4ee5u4e3bu4f1au6837u5e74u60f3u751fu540cu8001u4e2du5341u4eceu81eau9762u524du5934u9053u5b83u540eu7136u8d70u5f88u50cfu89c1u4e24u7528u5979u56fdu52a8u8fdbu6210u56deu4ec0u8fb9u4f5cu5bf9u5f00u800cu5df1u4e9bu73b0u5c71u6c11u5019u7ecfu53d1u5de5u5411u4e8bu547du7ed9u957fu6c34u51e0u4e49u4e09u58f0u4e8eu9ad8u624bu77e5u7406u773cu5fd7u70b9u5fc3u6218u4e8cu95eeu4f46u8eabu65b9u5b9eu5403u505au53ebu5f53u4f4fu542cu9769u6253u5462u771fu5168u624du56dbu5df2u6240u654cu4e4bu6700u5149u4ea7u60c5u8defu5206u603bu6761u767du8bddu4e1cu5e2du6b21u4eb2u5982u88abu82b1u53e3u653eu513fu5e38u6c14u4e94u7b2cu4f7fu5199u519bu5427u6587u8fd0u518du679cu600eu5b9au8bb8u5febu660eu884cu56e0u522bu98deu5916u6811u7269u6d3bu90e8u95e8u65e0u5f80u8239u671bu65b0u5e26u961fu5148u529bu5b8cu5374u7ad9u4ee3u5458u673au66f4u4e5du60a8u6bcfu98ceu7ea7u8ddfu7b11u554au5b69u4e07u5c11u76f4u610fu591cu6bd4u9636u8fdeu8f66u91cdu4fbfu6597u9a6cu54eau5316u592au6307u53d8u793eu4f3cu58ebu8005u5e72u77f3u6ee1u65e5u51b3u767eu539fu62ffu7fa4u7a76u5404u516du672cu601du89e3u7acbu6cb3u6751u516bu96beu65e9u8bbau5417u6839u5171u8ba9u76f8u7814u4ecau5176u4e66u5750u63a5u5e94u5173u4fe1u89c9u6b65u53cdu5904u8bb0u5c06u5343u627eu4e89u9886u6216u5e08u7ed3u5757u8dd1u8c01u8349u8d8au5b57u52a0u811au7d27u7231u7b49u4e60u9635u6015u6708u9752u534au706bu6cd5u9898u5efau8d76u4f4du5531u6d77u4e03u5973u4efbu4ef6u611fu51c6u5f20u56e2u5c4bu79bbu8272u8138u7247u79d1u5012u775bu5229u4e16u521au4e14u7531u9001u5207u661fu5bfcu665au8868u591fu6574u8ba4u54cdu96eau6d41u672au573au8be5u5e76u5e95u6df1u523bu5e73u4f1fu5fd9u63d0u786eu8fd1u4eaeu8f7bu8bb2u519cu53e4u9ed1u544au754cu62c9u540du5440u571fu6e05u9633u7167u529eu53f2u6539u5386u8f6cu753bu9020u5634u6b64u6cbbu5317u5fc5u670du96e8u7a7fu5185u8bc6u9a8cu4f20u4e1au83dcu722cu7761u5174u5f62u91cfu54b1u89c2u82e6u4f53u4f17u901au51b2u5408u7834u53cbu5ea6u672fu996du516cu65c1u623fu6781u5357u67aau8bfbu6c99u5c81u7ebfu91ceu575au7a7au6536u7b97u81f3u653fu57ceu52b3u843du94b1u7279u56f4u5f1fu80dcu6559u70edu5c55u5305u6b4cu7c7bu6e10u5f3au6570u4e61u547cu6027u97f3u7b54u54e5u9645u65e7u795eu5ea7u7ae0u5e2eu5566u53d7u7cfbu4ee4u8df3u975eu4f55u725bu53d6u5165u5cb8u6562u6389u5ffdu79cdu88c5u9876u6025u6797u505cu606fu53e5u533au8863u822cu62a5u53f6u538bu6162u53d4u80ccu7ec6";
    int x = 5;
    // 控制字数
    for (int i = 0; i < 4; i++) {
      // 设置字体旋转角度
      int degree = new Random().nextInt() % 30;
      // 截取汉字
      String ch = base.charAt(new Random().nextInt(base.length())) + "";
      sb.append(ch);
      // 正向角度
      g.rotate(degree * Math.PI / 180, x, 20);
      g.drawString(ch, x, 20);
      // 反向角度
      g.rotate(-degree * Math.PI / 180, x, 20);
      x += 30;
    }
    return sb.toString();
  }
}

第三种  加减乘除方式  

package com.myFirstSpring.util;
 
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
 
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 

public class ValidateCodeUtils_algorithm extends HttpServlet {
 
 private static final long serialVersionUID = -1409007752285164213L;
 private static int width = 75;
 private static int height = 35; 
 // private static char[] ch =
 // "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789".toCharArray();
 private static char[] ch = "0123456789".toCharArray();
 private static char[] sf = "+-x".toCharArray();
 
 public void doGet(HttpServletRequest request, HttpServletResponse response)
 
 throws ServletException, IOException {
 
 this.doPost(request, response);
 
 }
 
 // 生成数字和字母的验证码
 public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
 processRequest(request, response);
 }
 
 protected void processRequest(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);
 // 在内存中创建图象
 BufferedImage image = new BufferedImage(width, height,
  BufferedImage.TYPE_INT_RGB);
 
 // 获取图形上下文
 Graphics g = image.getGraphics();
 
 // 生成随机类
 Random random = new Random();
 
 // 设定背景色
 g.setColor(getRandColor(200, 250));
 g.fillRect(0, 0, width, height);
 
 // 设定字体
 g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
 
 // 画边框
 // g.setColor(new Color());
 // g.drawRect(0,0,width-1,height-1);
 
 // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
 g.setColor(getRandColor(160, 200));
 for (int i = 0; i < 155; i++) {
  int x = random.nextInt(width);
  int y = random.nextInt(height);
  int xl = random.nextInt(12);
  int yl = random.nextInt(12);
  g.drawLine(x, y, x + xl, y + yl);
 }
 
 // 取随机产生的认证码(4位数字)
 StringBuffer sb = new StringBuffer();
 int index, len = ch.length;
 index = random.nextInt(len);
 g.setColor(new Color(random.nextInt(88), random.nextInt(188),
  random.nextInt(255)));
 g.setFont(new Font("Arial", Font.ITALIC, 20));// 输出的字体和大小
 g.drawString("" + ch[index], (0 * 15), 26);// 写什么数字,在图片的什么位置画
 sb.append(ch[index]);
 
 int index1, len1 = sf.length;
 index1 = random.nextInt(len1);
 g.setColor(new Color(random.nextInt(88), random.nextInt(188),
  random.nextInt(255)));
 g.setFont(new Font("Arial", Font.ITALIC, 20));// 输出的字体和大小
 g.drawString("" + sf[index1], (1 * 15), 26);// 写什么数字,在图片的什么位置画
 sb.append(sf[index1]);
 
 
 int index2, len2 = ch.length;
 index2 = random.nextInt(len2);
 g.setColor(new Color(random.nextInt(88), random.nextInt(188),
  random.nextInt(255)));
 g.setFont(new Font("Arial", Font.ITALIC, 20));// 输出的字体和大小
 
 if(String.valueOf(sf[index1]).equals("-")){
  if(Integer.parseInt(String.valueOf(ch[index])) < Integer.parseInt(String.valueOf(ch[index2]))){
  index2 = index;
  } 
 }
 
 g.drawString("" + ch[index2], (2 * 15) , 26);// 写什么数字,在图片的什么位置画
 sb.append(ch[index2]);
 
 
 g.setColor(new Color(random.nextInt(88), random.nextInt(188),
  random.nextInt(255)));
 g.setFont(new Font("Arial", Font.ITALIC, 20));// 输出的字体和大小
 g.drawString("=", (3 * 15) , 26);// 写什么数字,在图片的什么位置画
 sb.append("=");
 
 g.setColor(new Color(random.nextInt(88), random.nextInt(188),
  random.nextInt(255)));
 g.setFont(new Font("Arial", Font.ITALIC, 20));// 输出的字体和大小
 g.drawString("?", (4 * 15) , 26);// 写什么数字,在图片的什么位置画
 sb.append("?");
 
   g.drawLine(5, 3, 60, 35);
 // 将认证码存入SESSION
 int jg = 0;
 if(String.valueOf(sf[index1]).equals("+")){
  jg = Integer.parseInt(String.valueOf(ch[index])) + Integer.parseInt(String.valueOf(ch[index2]));
 }
 if(String.valueOf(sf[index1]).equals("-")){
  jg = Integer.parseInt(String.valueOf(ch[index])) - Integer.parseInt(String.valueOf(ch[index2]));
 }
 if(String.valueOf(sf[index1]).equals("x")){
  jg = Integer.parseInt(String.valueOf(ch[index])) * Integer.parseInt(String.valueOf(ch[index2]));
 }
 
 request.getSession().setAttribute("piccode", String.valueOf(jg));
 request.getSession().setAttribute(request.getSession().getId(), sb.toString());
 
 // 图象生效
 g.dispose();
 ServletOutputStream responseOutputStream = response.getOutputStream();
 // 输出图象到页面
 ImageIO.write(image, "JPEG", responseOutputStream);
 
 // 以下关闭输入流!
 responseOutputStream.flush();
 responseOutputStream.close();
  
 }
 
 protected void ValidateCode(HttpServletRequest request,
  HttpServletResponse response) throws ServletException, IOException {
 // 在内存中创建图象
 BufferedImage img = new BufferedImage(width, height,
  BufferedImage.TYPE_INT_RGB);
 // 得到该图片的绘图对象
 Graphics g = img.getGraphics();
 
 Random r = new Random();
 Color c = new Color(200, 150, 255);
 g.setColor(c);
 
 // 填充整个图片的颜色
 g.fillRect(0, 0, width, height);
 
 // 向图片中输出数字和字母
 StringBuffer sb = new StringBuffer();
 int index, len = ch.length;
 for (int i = 0; i < 4; i++) {
  index = r.nextInt(len);
  g
   .setColor(new Color(r.nextInt(88), r.nextInt(188), r
    .nextInt(255)));
  g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));// 输出的字体和大小
  g.drawString("" + ch[index], (i * 15) + 6, 18);// 写什么数字,在图片的什么位置画
  sb.append(ch[index]);
 }
 
 request.getSession().setAttribute("piccode", sb.toString());
 ServletOutputStream responseOutputStream = response.getOutputStream();
 ImageIO.write(img, "JPG", responseOutputStream);
 responseOutputStream.flush();
 responseOutputStream.close();
 }
 
 Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
 Random random = new Random();
 if (fc > 255)
  fc = 255;
 if (bc > 255)
  bc = 255;
 int r = fc + random.nextInt(bc - fc);
 int g = fc + random.nextInt(bc - fc);
 int b = fc + random.nextInt(bc - fc);
 return new Color(r, g, b);
 }
 
 
 public static String getPath(Class name) {
 String strResult = null;
 if (System.getProperty("os.name").toLowerCase().indexOf("window") > -1) {
  strResult = name.getResource("/").toString().replace("file:/", "")
   .replace("%20", " ");
 } else {
  strResult = name.getResource("/").toString().replace("file:", "")
   .replace("%20", " ");
 }
 return strResult;
 }
}

直接复制代码可以测试生成的方法 

前段调用方法如下所示

function flushVerifyImg() {
 var timenow = new Date().getTime(); 
  $("#VerifyImg").attr("src", '/servlet/Validate?d=' + timenow);
  return false;
}

然后是配置文件  在web.xml配置如下


  Validate
  com.myFirstSpring.util.ValidateCodeUtils
 
 
  Validate
  /servlet/Validate
 

其中重要的是一个你的文件路径需要配置正确 就是 com.myFirstSpring.util.ValidateCodeUtils

在放一下我的项目配置文件 



 CoBiker
 
  encodingFilter
  org.springframework.web.filter.CharacterEncodingFilter
  
   encoding
   UTF-8
  
  
   forceEncoding
   true
  
 
 
  encodingFilter
  *
 
 
  org.springframework.web.context.ContextLoaderListener
 
 
  action
  org.springframework.web.servlet.DispatcherServlet
  1
 
 
  action
  /
 
 
  Validate
  com.myFirstSpring.util.ValidateCodeUtils
 
 
  Validate
  /servlet/Validate
 
 
  index.ftl
 
 
  404
  /WEB-INF/view/404.ftl  
 
 
  500
  /index.ftl
 
 
  BASIC
 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/135383.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号