您的位置:首页 > 编程语言 > Java开发

Java随机生成验证码,并且转化成图片

2016-09-12 10:15 585 查看
package GUI;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics2D;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import java.util.Random;

import javax.imageio.ImageIO;

public class yan {
//用于验证码的字符串
private String[] str = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
"Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y",
"z", "2", "3", "4", "5", "6", "7", "8", "9" };
static String[] arry = new String[50];//一个字符串,存储验证码字符
public Random random = new Random();//建立一个随机数,可以用于获取字符
//public int cc;
Random r=new Random();//同上
String s;
//获取4个随机字符
public String getRandom() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < 4; i++) {
buffer.append(str[random.nextInt(str.length)]);
}
return buffer.toString();
}
//获取颜色,用于字体颜色
public Color getColor() {
return new Color(random.nextInt(255), random.nextInt(255),
random.nextInt(255));
}
//获取反颜色
public Color getreversColor(Color c) {
return new Color(255 - c.getRed(), 255 - c.getGreen(),
255 - c.getBlue());
}
//制造一张图片,画上字符串,涂上颜色
public yan() throws IOException {
int x = 100, y = 28;//图片大小
BufferedImage bi = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();//画板
g.setFont(new Font("隶书", Font.BOLD, 27));//字体颜色,大小,格式
s = getRandom();//获取随机字符串
String ss=s.toLowerCase();//变成小写,用于该图片的命名,可
File folder = new File("Random");//创建一个文件夹,用于存放图片
deleteFile(folder);//如果该文件夹存在,删除该文件夹,可以用于清除以前的验证码图片
if (!folder.exists())//如果不存在,创建
folder.mkdir();
File f = new File("Random/" + ss + ".jpg");//命名
// File f2=new File("Random/i"+cc+".jpg");
g.setColor(getColor());
g.fillRect(0, 0, x, y);
g.setColor(getreversColor(getColor()));
g.drawString(s, 18, 20);
//生成1-100个随机干扰点
for (int i = 0; i < r.nextInt(100); i++)
g.drawRect(r.nextInt(x), r.nextInt(y), 1, 1);
ImageIO.write(bi, "jpg", f);//保存
}
// public static void main(String[] args) throws IOException {
// new yan();
// }
public void deleteFile(File file) {
// TODO Auto-generated method stub
if (file.exists()) { // 判断文件是否存在
if (file.isFile()) { // 判断是否是文件
file.delete(); // delete()方法 删除;
} else if (file.isDirectory()) { // 否则如果它是一个目录
File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
this.deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
}
}
file.delete();
} else {
System.out.println("所删除的文件不存在!" + '\n');
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java