验证码生成器

package com.sfiec.oms.common.utils;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;


import javax.imageio.ImageIO;
/**
 * 验证码生成器
 *
 */
public class ValidateCode {
// 图片的宽度。
private int width = 60;
// 图片的高度。
private int height = 22;
// 验证码字符个数
private int codeCount = 4;
// 验证码
private String code = null;
// 验证码图片Buffer
private BufferedImage buffImg=null;


private char[] codeSequence = { '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',  '1', '2', '3', '4', '5', '6', '7', '8', '9' };


public  ValidateCode() {
this.createCode();
}


public  ValidateCode(int width,int height) {
this.width=width;
this.height=height;
this.createCode();
}

public  ValidateCode(int width,int height,int codeCount) {
this.width=width;
this.height=height;
this.codeCount=codeCount;
this.createCode();
}

@SuppressWarnings("unused")
public void createCode() {
int x = 0;
int fontHeight=0;
int codeY=0;
int red = 0 ;
int green = 0;
int blue = 0;
x = width / (codeCount +1)-1;
fontHeight = height - 2;
codeY = height - 12;

buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
Random random = new Random();
// 将图像填充为白色
g.setColor(new Color(229,195,212));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman",Font.PLAIN,22));

StringBuffer randomCode = new StringBuffer();
for (int i = 0; i < codeCount; i++) {
String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
g.setColor(new Color(97, 45, 111));
g.drawString(strRand, (i + 1) * x, codeY);
randomCode.append(strRand);
}
code=randomCode.toString();
}

public void write(String path) throws IOException {
OutputStream sos = new FileOutputStream(path);
this.write(sos);
}

public void write(OutputStream sos) throws IOException {
ImageIO.write(buffImg, "png", sos);
sos.close();
}
public BufferedImage getBuffImg() {
return buffImg;
}

public String getCode() {
return code;
}
}

猜你喜欢

转载自blog.csdn.net/tyt1002/article/details/79579601
今日推荐