java中生成验证码

代码工具类

废话不多话,直接上代码

package com.ls.mytest;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
* 生成验证码的公共类    黄思博
*/
public class CodeUtil {

   /**
    * 图片的宽度
    * */
   private static int width = 80;
   
   /**
    * 图片的高度
    * */
   private static int height = 20;
   
   /**
    * 验证码数字的个数
    * */
   private static int codeCount = 4;
   
   /**
    * 基础数字,不采用英文字,o和0有点分不清
    * */
   private static String codeSequence = "0123456789";
   
   private static int xx = 15;
   private static int fontHeight = 18;
   private static int codeY = 15;
   

   /**
    * 生成一个map集合
    * code为生成的验证码
    * codePic为生成的验证码BufferedImage对象
    *
    * @return
    */
   public static Map<String, Object> getRandomNum() {
       //定义图像buffer
       BufferedImage buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
       Graphics gp = buffImage.getGraphics();
       //创建随机生成    
       Random random = new Random();
       //设置图片属性
       gp.setColor(new Color(0xB5BDDC));
       gp.fillRect(0, 0, width, height);
       //设置字体属性
       Font font = new Font("", Font.ITALIC | Font.BOLD, fontHeight);
       gp.setFont(font);
       //设置边框
       gp.setColor(Color.BLACK);
       gp.drawRect(0, 0, width - 1, height - 1);
       //buff存数字
       StringBuffer ranomNum = new StringBuffer();
       for (int i = 0; i < codeCount; i++) {
           int ranomNumber = random.nextInt(codeSequence.length());
           ranomNum.append(codeSequence.charAt(ranomNumber));
       }
       gp.drawString(ranomNum.toString(),xx,codeY);
       //存放
       Map<String,Object> hashMap=new HashMap<>(16);
       hashMap.put("code", ranomNum);
       hashMap.put("codePic", buffImage);
       return hashMap;
   }
}

main也直接贴上

 public static void main(String[] args) throws Exception {
       FileOutputStream fileOutputStream = new FileOutputStream("D://img//"+System.currentTimeMillis()+".jpg");

       Map<String, Object> randomCode = CodeUtils.getRandomCode();

       ImageIO.write((RenderedImage)randomCode.get("codePic"),"JPEG",fileOutputStream);

       System.out.println("随机验证码为:"+randomCode.get("code").toString());

   }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值