java工具类验证码生成

工具类:

package com.yunhe.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Random;

public class VCodeUtils {
    private int w = 100;    //设置图片宽度
    private int h = 40;        //设置图片高度
    private Color bgColor = new Color(255, 255, 255);        //设置图片背景
    Random random = new Random();
    StringBuilder sb = new StringBuilder();

    private BufferedImage createImage() {
        /**
         * 1.创建图片
         * 2.设置背景色
         */
        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        //设置画笔颜色
        Graphics2D graphics2d = (Graphics2D) img.getGraphics();
        graphics2d.setColor(this.bgColor);
        graphics2d.fillRect(0, 0, w, h);
        //填充图片大小的矩形(设置背景色)
        return img;
    }

    private Color randomColor() {
        int r = random.nextInt(256);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        return new Color(r, g, b);
    }

    /**
     * 设置 字体、字号、样式
     *
     * @return
     */
    private String[] fontName = {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑"};
    private int[] fontSize = {28, 32, 35, 39, 45};

    private Font randomFont() {
        int index = random.nextInt(fontName.length);
        //根据随机索引获取字体名
        String name = fontName[index];
        //设置字体样式
        int style = random.nextInt(4);
        index = random.nextInt(fontSize.length);
        //根据索引获取字体大小
        int size = fontSize[index];
        return new Font(name, style, size);
    }

    private String codes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRESTUVWXYZ0123456789";

    private String randomChar() {
        int index = random.nextInt(codes.length());
        //返回随机字符
        return codes.charAt(index) + "";
    }

    private void drawLine(BufferedImage image) {
        int num = 6;
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        for (int i = 0; i < num; i++) {
            int x1 = random.nextInt(w);
            int y1 = random.nextInt(h);
            int x2 = random.nextInt(w);
            int y2 = random.nextInt(h);
            g2.setStroke(new BasicStroke(1.5F));
            g2.setColor(this.randomColor());
            g2.drawLine(x1, y1, x2, y2);
        }
    }

    public BufferedImage getImage() {
        /**
         * 写入字符(包括字符字体、颜色、字符种类)
         */
        BufferedImage img = this.createImage();
        Graphics g = img.getGraphics();
        for (int i = 0; i < 4; i++) {
            //设置字符
            String ch = this.randomChar();
            sb.append(ch);
            //设置画笔颜色
            g.setColor(this.randomColor());
            //设置画笔字体
            g.setFont(this.randomFont());
            //画出字符
            g.drawString(ch, w / 4 * i, h - 5);
        }
        drawLine(img);
        return img;
    }

    //获取验证码的字符
    public String getText() {
        return sb.toString();
    }

    public static void saveImage(BufferedImage img, OutputStream out) throws Exception {
        ImageIO.write(img, "JPEG", out);
    }

    public static void main(String[] args) {
        try {
            VCodeUtils vc = new VCodeUtils();
            saveImage(vc.getImage(), new FileOutputStream("E:/11.jpg"));
            System.out.println(vc.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

应用:

package com.yunhe.controller;

import com.yunhe.utils.VCodeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 生成验证码
 */
@Controller
@RequestMapping("verify")
public class VerifyCodeController {

    @RequestMapping("code")
    public void generateCode(HttpServletResponse response, HttpSession session){
        VCodeUtils vc = new VCodeUtils();
        try {
            response.setContentType("images/*");
            VCodeUtils.saveImage(vc.getImage(), response.getOutputStream());
            String verifyCode = vc.getText();
            session.setAttribute("verifyCode",verifyCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

验证码判断代码:

//验证码
        if(StringUtils.isBlank(verifyCode)){
            model.addAttribute("msg","请输入验证码!");
            return "../../index";
        }

        //验证码正确与否
        if(!verifyCode.equalsIgnoreCase(session.getAttribute("verifyCode").toString())){
            model.addAttribute("msg","验证码输入错误!");
            return "../../index";
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值