栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java生成图片验证码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java生成图片验证码

 生成验证码工具类:

package com.qxs.utils;

import java.util.Random;
import java.io.IOException;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CodeUtils {
    private static int width = 220;// 验证码宽度
    private static int height = 70;// 验证码高度
    private static Random random = new Random();
    
    public static void getCode(HttpServletRequest request, HttpServletResponse response, int len) throws IOException {
        // 创建一张空白图片,宽度,高度,图片类型
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 获取到画笔
        Graphics g = image.getGraphics();

        // 给画笔设置颜色
        g.setColor(randomColor());

        // 使用画笔填充一个矩形
        g.fillRect(0,0, width, height);

        // 得到随机验证码
        String code = randomCode(len);

        // 把验证码存入session
        request.getSession().setAttribute("vcode", code);

        
        g.setFont(new Font(null,Font.BOLD+Font.ITALIC, height/2));

        // 把验证码画到图画上。
        for (int i = 0; i < code.length() ; i++) {
            char c = code.charAt(i);// 取出一个字符
            // 给画笔设置一个颜色
            g.setColor(randomColor());
            // 在图片上面写字
            
            int w = width / (len + 1);
            g.drawString(c+"",w + i*w - (w/2), 45);
        }

        // 画干扰线
        for (int i = 0; i < 5; i++) {
            g.setColor(randomColor());
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }

        // 画干扰雪花
        for (int i = 0; i < 5; i++) {
            g.setColor(randomColor());
            int x = random.nextInt(width+1);
            int y = random.nextInt(height+1);
            g.drawString("*", x, y);
        }

        
        ImageIO.write(image,"png", response.getOutputStream());
    }

    // 随机获取一个颜色
    private static Color randomColor() {
        int r = random.nextInt(256),
            g = random.nextInt(256),
            b = random.nextInt(256);
        return new Color(r, g, b);
    }

    // 获取随机的验证码
    public static String randomCode(int len){
        StringBuilder sb = new StringBuilder();
        char[] arr = "0123456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ".toCharArray();
        //随机产生四位索引值,然后分别取出字符
        for (int i = 0; i < len; i++) {
            int index = random.nextInt(arr.length);
            sb.append(arr[index]);
        }
        return sb.toString();
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/672387.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号