Java生成验证码

开发工具与关键技术:Eclipse 生成验证码
作者:卢远平
撰写时间:2020.08.07

//先是用到的包。
package com.gx.utils;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class ios {
//在方法中给map集合指定范行
public Map<String, Object> oijs() {
//接着是创建图片,设置宽高,图片颜色模式。
int width = 60;
int height = 44;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//接着创建图层获得画板。
Graphics qq = image.getGraphics();
//接着设置画笔的颜色
qq.setColor(Color.BLACK);
//然后是设置验证码取值范围
qq.fillRect(0, 0, width - 2, height - 2);
String dataString=“ABCDEFGHIJHLMNOPQR
STUVWXYZabcdefghijklmnopqlstuvwxyz1234567890”;
//设置字体
qq.setFont(new Font(“宋体”, Font.BOLD, 30));
//缓存随机生成的字符
StringBuffer dd= new StringBuffer();
Random random = new Random();
// 截取字符
for (int i = 0; i < 4; i++) {
// 设置字体颜色 随机
qq.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
// 获得一个随机字符
int index = random.nextInt(62);
String str = dataString.substring(index, index + 1);
// 加入画板
qq.drawString(str, 20 * i, 30);
dd.append(str);}
// 干扰线
for (int i = 0; i < 10; i++) {
qq.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
qq.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
}
//创建map集合,然后把验证码的值和图片存入,然后可以通过键值来获取,如果不需要获取验证码值就把方法改为:public static BufferedImage oijs,然后下面的集合不要。
Map<String, Object> io = new HashMap<String, Object>(); io.put(“k2”, dd);
io.put(“k3”, image);
return io;
}
}
Java生成验证码