代码工具类
废话不多话,直接上代码
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());
}