importjavax.imageio.ImageIO;import java.awt.*;importjava.awt.image.BufferedImage;importjava.io.IOException;importjava.io.OutputStream;importjava.util.Random;public classCaptchaUtils {private final static Object lock = newObject();/*** 图片的宽度。*/
private int width = 132;/*** 图片的高度。*/
private int height = 40;/*** 验证码字符个数*/
private int codeCount = 4;/*** 验证码干扰线数*/
private int lineCount = 10;private staticCaptchaUtils instance;static{synchronized(lock) {if (instance == null) {
instance= newCaptchaUtils();
}
}
}public staticCaptchaUtils getInstance() {returninstance;
}private static final char[] codeSequence ={'A', 'B', 'C', 'D', 'E', 'F', 'G','H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T','U', 'V', 'W', 'X', 'Y', 'Z','1', '2', '3', '4', '5', '6', '7', '8', '9'};publicString createCode() {
Random random= newRandom(System.currentTimeMillis());
StringBuffer buffer= newStringBuffer();for (int i = 0; i < codeCount; i++) {
String strRand=String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
buffer.append(strRand);
}returnbuffer.toString().toLowerCase();
}public voiddraw(String code, OutputStream sos) {
BufferedImage bufferedImage= this.drawCode(code);try{
ImageIO.write(bufferedImage,"png", sos);
sos.close();
}catch(IOException e) {
e.printStackTrace();
}
}privateBufferedImage drawCode(String code) {int x = 0, fontHeight = 0, codeY = 0;int red = 0, green = 0, blue = 0;//生成随机数
Random random = newRandom(System.currentTimeMillis());//每个字符的宽度
x = width /codeCount;//字体的高度
fontHeight = height - 8;
codeY=height;//图像buffer
BufferedImage buffImg = newBufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g=buffImg.createGraphics();//将图像填充为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
Font font= new Font("Arial", Font.PLAIN, fontHeight);
g.setFont(font);for (int i = 0; i < lineCount; i++) {
red= random.nextInt(255);
green= random.nextInt(128) + 127;
blue= random.nextInt(128) + 127;
g.setColor(newColor(red, green, blue));//初始角度必须大于0
int angRange = random.nextInt(270) + 30;int arcX = random.nextInt(width) - (width >> 4);int arcY =random.nextInt(height);int arcWidth =random.nextInt(width);int arcHeight =random.nextInt(height);int arcStartAng = random.nextInt(angRange) + 1;int arcAng = random.nextInt(angRange) + 1;
g.drawArc(arcX, arcY, arcWidth, arcHeight, arcStartAng, arcAng);
}int offsetX = random.nextInt(5) + 5;int offsetY = random.nextInt(5) + 10;for (int i = 0; i < code.length(); i++) {
String strRand= code.substring(i, i + 1);//产生随机的颜色值,让输出的每个字符的颜色值都将不同。
red = random.nextInt(255);
green= random.nextInt(127);
blue= random.nextInt(255);
g.setColor(newColor(red, green, blue));//正负波动微调
double degree = (random.nextInt(20) - 10) * Math.PI / 180;int fx = (i * x) +offsetX;int fy = codeY -offsetY;
g.rotate(degree, fx, fy);
g.drawString(strRand, fx, fy);//输出完成旋转回来
g.rotate(-degree, fx, fy);
}returnbuffImg;
}
}