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

随机生成图片验证码

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

随机生成图片验证码

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;


public class ImageCode {
    public static void main(String[] args) throws IOException {
        imageCode();
    }

    //生成随机验证码的方法
    private static void imageCode() throws IOException {
        //准备生成验证码的数据
        String[] strs={"a","b","c","d","e","f","g","h","i","j","k","m","n","p"
        ,"q","r","s","t","u","v","w","x","y","z","2","3","4","5","6","7","8","9"};

        //准备一个画板,用来承载验证码,参数(宽,高,图片类型)字母,数字,干扰线
        int width = 150;
        int height = 50;
        int imageType = BufferedImage.TYPE_INT_RGB;
        BufferedImage image = new BufferedImage(width,height,imageType);

        //准备一只画笔
        Graphics graphics = image.getGraphics();
        //设置画笔的颜色
        graphics.setColor(Color.green);
        //画填充矩形
        graphics.fillRect(0,0,width,height);

        //画验证码
        //从数组中随机取出4个数据
        //设置验证码的位置
        Random random = new Random();
        int x = 30;
        int y=30;
        //修改画笔颜色
        graphics.setColor(Color.red);
        graphics.setFont(new Font("楷体",Font.BOLD,30));
        for (int i = 0; i < 4; i++) {
            //随机生成num
            //获取随机的下标数
            Integer num =  random.nextInt(strs.length);
            String code = strs[num];
            //将验证码画到画板上
            graphics.drawString(code,x,y);
            x=x+25; //修改验证码位置
        }

        graphics.setColor(Color.blue);
        //画干扰线
        for (int i = 0; i < 5 ; i++) {
            int x1 = random.nextInt(50);
            int y1 = random.nextInt(50);
            int x2 = random.nextInt(30);
            int y2 = random.nextInt(27);
           graphics.drawLine(x1,y1,x2,y2);
        }
        graphics.setColor(Color.orange);
        for (int i = 0; i < 5 ; i++) {
            int x1 = random.nextInt(30);
            int y1 = random.nextInt(20);
            int x2 = random.nextInt(50)+120;
            int y2 = random.nextInt(30);
            graphics.drawLine(x1,y1,x2,y2);
        }

       //将验证码图片写到本地
        ImageIO.write(image,"jpg", new File("C:\Users\xiaoXue\Desktop\imageCode.jpg"));
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/781996.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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