[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();
}
}
|