您的位置:首页 > 其它

使用AWT组件实现验证码功能

2013-09-10 12:08 447 查看
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
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 Test {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//用于随机生成验证码的字符串集
String[] strs = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R"
,"S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j"
,"k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1"
,"2","3","4","5","6","7","8","9"};
//随机生成干扰线的纵坐标y1和y2
Random y1Random = new Random();
Random y2Random = new Random();
int y1 = y1Random.nextInt(31);
int y2 = y2Random.nextInt(31);

//随机生成用于组成验证码的字符串所在集的下标值
Random code1Random = new Random();
Random code2Random = new Random();
Random code3Random = new Random();
Random code4Random = new Random();
int code1Index = code1Random.nextInt(62);
int code2Index = code2Random.nextInt(62);
int code3Index = code3Random.nextInt(62);
int code4Index = code4Random.nextInt(62);

//随机生成rgb颜色
Random rRandom = new Random();
Random gRandom = new Random();
Random bRandom = new Random();
int r = rRandom.nextInt(256);
int g = gRandom.nextInt(256);
int b = bRandom.nextInt(256);
Color color = new Color(r, g, b);

//拼接成完整字符串
String codeString = strs[code1Index] + strs[code2Index] + strs[code3Index] + strs[code4Index];

//定义一个宽70像素,高30像素的jpg图片
BufferedImage bi = new BufferedImage(70, 30, BufferedImage.TYPE_INT_RGB);
//定义graphis绘画对象
Graphics2D graphics2d = bi.createGraphics();
graphics2d.setBackground(Color.WHITE);
graphics2d.setColor(color);
graphics2d.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
graphics2d.clearRect(0, 0, 70, 30);
       //绘制干扰线
graphics2d.drawLine(0, y1, 70, y2);

//居中绘制字符串
FontMetrics fontMetrics = graphics2d.getFontMetrics();
int stringWidth = fontMetrics.stringWidth(codeString);
int stringAscent = fontMetrics.getAscent();
int xCode = 70 / 2 - stringWidth / 2;
int yCode = 30 / 2 + stringAscent / 2;
graphics2d.drawString(codeString, xCode, yCode);

//输出图片
File file = new File("C:\\Users\\zhengbing\\Desktop\\image.jpg");
ImageIO.write(bi, "jpeg", file);
}

}


最后可以返回校验字符串codeString,来达到验证的功能
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: