吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 3353|回复: 5
收起左侧

[Java 转载] java BufferedImage Graphics 绘制验证码

[复制链接]
Vvvvvoid 发表于 2016-12-6 22:56






[Java] 纯文本查看 复制代码
package test;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Random;
/**
 * Created by void on 2016-12-06.
 */
public class Demo {
    static ArrayList<Character> arrayList = new ArrayList<>();
    static {
        // 把所有字母和数字的对应 字符 存到一个集合中 .
        char small = 'a';
        char big = 'A';
        char num = '0';
        for (int i = 0; i < 26; i++) {
            if (i < 10) {
                arrayList.add(num++);
            }
            arrayList.add(small++);
            arrayList.add(big++);
        }
    }
    public static void main(String[] args) throws SQLException {
        // 获取随机验证码  a-zA-Z0-9
        String veryfiCode = veryfiCode();
        BufferedImage image = new BufferedImage(70, 25, BufferedImage.TYPE_INT_BGR);
        // 相当于得到一支笔
        Graphics graphics = image.getGraphics();
        // 设置背景颜色 默认白色
        graphics.setColor(Color.black);
        graphics.fillRect(0, 0, 70, 30);
        // 设置画笔的颜色
        graphics.setColor(Color.red);
        // 设置字体的属性
        graphics.setFont(new Font(Font.SERIF, Font.TYPE1_FONT, 25));
        // 将随机字符画到图片上
        graphics.drawString(veryfiCode, 5, 18);
        // 在当前目录下生成该图片
        File file = new File(veryfiCode + ".png");
        try {
            ImageIO.write(image, "png", file);
            System.out.println("成功 : \t" + file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("失败");
        }
    }
    public static String veryfiCode() {
        Random random = new Random();
        StringBuffer code = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            int nextInt = random.nextInt(arrayList.size());
            Character character = arrayList.get(nextInt);
            code.append(character);
        }
        return code.toString();
    }
}

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

wmg13178599398 发表于 2016-12-6 23:22
沙发暖贴
palard 发表于 2016-12-6 23:57
dszsdyx 发表于 2016-12-7 04:17
yssun 发表于 2016-12-7 08:58
高手啊。。  
www478347671 发表于 2016-12-7 16:12
到jsp里执行生成比较好、
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-6-7 13:56

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表