Java实现验证码
步骤:
1)选取4个随机的字母或数字
2)创建缓冲图片
3)创建绘图对象
4)使用绘图对象绘制随机的字母或数字
5)将生成的验证码输出
代码实现:
public static void main(String[] args) throws Exception {
int width = 200;
int height = 100;
//缓存图片
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
//画笔对象
Graphics graphics = bufferedImage.getGraphics();
//白色容器
graphics.setColor(new Color(255, 255, 255));
graphics.fillRect(0, 0, width, height);
//验证码,制作开始
//颜色
graphics.setColor(new Color(0, 0, 0));
//字体
graphics.setFont(new Font("黑体", Font.BOLD, 40));
//随机码
String randomCode = UUID.randomUUID().toString().replace("-", "").substring(0, 4);
//进行绘制
graphics.drawString(randomCode, 54, 64);
//干扰信息
//线
Random r = new Random();
for (int i = 0; i < 15; i++) {
graphics.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
graphics.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
}
//点
for (int i = 0; i < 150; i++) {
graphics.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
//开始画点,实质上这是画椭圆,将上半轴半径,左半轴半径设置为0就可以看成是一个点
graphics.drawOval(r.nextInt(width), r.nextInt(height), 0, 0);
}
//输出
FileOutputStream fos = new FileOutputStream("/Users/liuqiang/Documents/project/gltf-ue/ok.png");
ImageIO.write(bufferedImage, "png", fos);
fos.close();
}
代码解释:
图形的绘制API:
BufferedImage 缓冲图片(保存在内存中的图片)
Graphics 图形
setColor(Color color) 设置颜色
setFont(Font font) 设置字体
fillRect(横坐标,纵坐标,宽,高) 填充矩形
drawLine(横坐标,纵坐标,横坐标,纵坐标) 绘制线条
drawString(String text,横坐标,纵坐标) 绘制文字