Java 生成验证码图片

验证码的作用:区分开 机器 与 人 (比如防止恶意注册)

直接上 代码 与 效果图 (我想要的真正的效果还没有时间做出来,先这么凑合着用)

工具类:

VerificationCdoe

package com.zh.seckillsystemtwo.util;

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

/**
 * CREATE BY OUKELE
 * CREATE TIME:2020/5/10 - 1:17
 * 生成算术验证码
 */
public class VerificationCode {

    private static  String[] randomStr = {"0", "1", "2", "3", "4",
            "5", "6", "7", "8", "9", "A", "B",
            "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
            "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z"};

    public static Object getVerificationCode(){

        // 定义验证码图片大小
        int width = 200,height = 50;
        // 在内存中创建 图像
        BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        // 为内存中要创建的图像生成画布,
        Graphics2D graphics2D = bufferedImage.createGraphics();
        // 画一个白色矩形,作为验证码背景
        graphics2D.setColor(Color.LIGHT_GRAY);
        // 填充
        graphics2D.fillRect(0,0,width,height);

        // 画 100 条 灰色的 随机干扰线
        graphics2D.setColor(Color.GRAY);
        Random random = new Random();
        for (int i = 0; i < 100; i++) {
            graphics2D.drawLine(random.nextInt(width),random.nextInt(height),random.nextInt(width),random.nextInt(height));
        }

        // 创建字体
        Font font = new Font("Times New Roman",Font.BOLD , 25);
        graphics2D.setFont(font);

        // 设置默认生成 4个 长度的验证码
        int strLength = 4;
        StringBuffer str = new StringBuffer();
        // 取得 4 位数的 随机字符串
        for (int i = 0; i < strLength; i++) {
            // 返回一个 随机数,在 1 和 20 之间
            String randomNumber = String.valueOf(  randomStr[ random.nextInt(36) ] );
            int red = random.nextInt(255);
            int green = random.nextInt(255);
            int blue = random.nextInt(255);
            //获得一个随机红蓝绿的配合颜色
            graphics2D.setColor(new Color(red, green, blue));
            //把该数字用画笔在画布画出,并指定数字的坐标
            graphics2D.drawString(randomNumber, 50 * i + 6, (height / 2)  + 10);
            //把该数字加到缓存字符串中。用于等会生成验证码字符串set到session中用于校对
            str.append(randomNumber);
        }
        // 清除内存的图片
        bufferedImage.flush();
        // 释放资源
        graphics2D.dispose();

        // 返回结果
        Map result = new HashMap();
        result.put("imgStream",bufferedImage);
        result.put("code",str);
        return result;
    }

    public static void main(String[] args) {

    }

}

使用:

Java 生成验证码图片

效果:

Java 生成验证码图片

另一种使用方式:(字节形式)

Java 生成验证码图片

Java 生成验证码图片

效果:(注意需要加上前缀,不然 img 标签 无法 解析,data:image/jpg;base64,)

Java 生成验证码图片

Original: https://www.cnblogs.com/oukele/p/12869137.html
Author: 追梦滴小蜗牛
Title: Java 生成验证码图片

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/537589/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球