web.xml 配置对应路径
package com.shancai.controller.rand;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
/**
* 一个能生成验证码的类
* 默认四个汉字
* 使用该类生成验证码时
* @author
*/
public class VerifyCodeASNI {
private final Random random = new Random(System.nanoTime());
private int width;
private int height;
private int charNumber = 4;
private float yawpRate = 0.05f; //噪声率
private OutputStream outputStream;
private char[] code;
private char[] code2;
private List codelist;
public VerifyCodeASNI() {
//empty
}
/**
* 返回生成的验证码字符串
* @return
*/
public String getVerifyCode(){
return getStr(codelist);
}
public VerifyCodeASNI(int width, int height) {
this.width = width;
this.height = height;
}
private void drawPane(Graphics2D g2d){
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(2.0f));
g2d.drawRect(0, 0, width, height);
}
private void drawChars(Graphics2D g2d){
float scale = 1f;
int size = (int) (scale * 30);
StringBuffer sb = new StringBuffer(1);
sb.setLength(1);
g2d.setColor(Color.BLACK);
// code = new char[charNumber];
for (int i = 0; i < charNumber; i++) {
//计算第i个字的x偏移
int offsetWidth = i * (size+1)+10;
//随机大小
int charSize = size;//this.getRandomIntBetween((int) (size * 0.5), size);
//随机样式
int fontStyle = this.getRandomBoolean() ? Font.ITALIC : Font.ITALIC;
g2d.setFont(new Font("隶书", fontStyle, charSize));
//随机颜色
//g2d.setColor(this.getRandomColor());
//随机上移一点
int moveUp = random.nextInt((int) (0.1 * offsetWidth));
//随机字符
sb.setCharAt(0, code[i]);
g2d.drawString(sb.toString(), offsetWidth-moveUp, 45);
}
}
private void drawCharsbody(Graphics2D g2d,int head){
float scale = 1f;
int size = (int) (scale * 30);
StringBuffer sb = new StringBuffer(1);
sb.setLength(1);
g2d.setColor(Color.BLACK);
int offsetWidth;
int moveup;
int v = 30;
int w = 15;
if(head<3){
offsetWidth = head * (size+15)+w;
moveup =70 + v *1;
}else if(head<6){
offsetWidth = (head-3) * (size+15)+w;
moveup =70 + v *2;
}
else{
offsetWidth = (head-6) *(size+15)+w;
moveup =70 + v *3;
}
//计算第i个字的x偏移
//随机大小
int charSize = size;//this.getRandomIntBetween((int) (size * 0.5), size);
//随机样式
int fontStyle = this.getRandomBoolean() ? Font.ITALIC : Font.ITALIC;
g2d.setFont(new Font("隶书", fontStyle, charSize));
//随机颜色
//g2d.setColor(this.getRandomColor());
//随机上移一点
// int moveUp = 0;//random.nextInt((int) (0.3 * height));
//随机字符
sb.setCharAt(0, code2[head]);
g2d.drawString(sb.toString(), offsetWidth,moveup);
}
private String getStr(List list){
StringBuffer sb = new StringBuffer();
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false);
nf.setMaximumIntegerDigits(5);
nf.setMinimumIntegerDigits(5);
for (int i = 0; i < list.size(); i++) {
sb.append(nf.format(Integer.parseInt(Integer.toBinaryString(list.get(i)))));
}
return sb.toString();
}
/**
* 主要方法,开始生成
*/
public void write() {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, width, height);
//绘制干扰线
Random random = new Random();
g2d.setColor(getRandColor(160, 200));// 设置线条的颜色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(120 - 1);
int y = random.nextInt(20 - 1);
int xl = random.nextInt(7) + 1;
int yl = random.nextInt(12) + 1;
g2d.drawLine(x, y, x + xl + 40, y + yl + 20);
}
this.getCode();
//画方框9/10期望宽度
this.drawPane(g2d);
//设定字体,字体大小为4/5方框,居中
this.drawChars(g2d);
for (int i = 0; i < 9; i++) {
this.drawCharsbody(g2d,i);
}
/*补充注释:有些人添加干扰时,喜欢使用随机线条。我认为这个方法一点都不好,不仅是图片极度丑陋,而且根本起不到干扰的作用。*/
//背景上随机10行小字
// this.drawSmallChars(g2d);
Color c = getRandColor(200, 250);
shear(g2d, 150, 50, c);// 使图片扭曲
//添加噪点
int area = (int) (this.getYawpRate() * height * width);
for (int i = 0; i < area; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int rgb = this.getRandomIntColor();
// bi.setRGB(x, y, rgb);
}
try {
ImageIO.write(bi, "jpeg", outputStream);
} catch (Exception exc) {
exc.printStackTrace();
}
}
private boolean getRandomBoolean() {
int randInt = random.nextInt(10);
if (randInt > 4) {
return true;
} else {
return false;
}
}
private void getCode(){
code = new char[4];
for (int i = 0; i < 4; i++) {
code[i] = this.getRandomChar();
}
code2 = new char[9];
codelist = new ArrayList();
while (true) {
Random random = new Random();
int de = random.nextInt(9);
if(codelist.size()>3){
break;
}
if(codelist.indexOf(de)<0){
codelist.add(de);
}
System.out.println(codelist.toString());
}
for (int i = 0; i < codelist.size(); i++) {
code2[codelist.get(i)]=code[i];
}
for (int i = 0; i < code2.length; i++) {
String date = String.valueOf(code2[i]).trim();
if("".equals(date)){
code2[i] = getRandomChar();
}
}
}
private Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private int getRandomIntColor() {
int[] rgb = this.getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
/**
* 返回一个随机汉字字符。
* 采用随机生成两个byte按gb2312编码构成一个String的算法。
* 两个字节在B0A1到D7F9之间,是常用简体字
* 所以,第一个字节在B0(十进制176)到D7(十进制215)之间,第二个字节在A1(十进制161)到F9(十进制249)之间
* @return
*/
protected char getRandomChar() {
final int minFirstByte = 176;
final int maxFirstByte = 215;
final int minSecondByte = 161;
final int maxSecondByte = 249;
byte[] b = new byte[2];
b[0] = (byte) (getRandomIntBetween(minFirstByte, maxFirstByte));
b[1] = (byte) (getRandomIntBetween(minSecondByte, maxSecondByte));
try {
String s = new String(b, "gb2312");
assert s.length() == 1;
return s.charAt(0);
} catch (UnsupportedEncodingException uee) {
//重试
return getRandomChar();
}
}
/**
* 获取两个整数之间的某个随机数,包含较小的整数,不包含较大的整数
* @param first
* @param second
* @return 随机数
*/
private int getRandomIntBetween(int first, int second) {
if (second < first) {
int tmp = first;
first = second;
second = tmp;
}
return random.nextInt(second - first) + first;
}
public int getWidth() {
return width;
}
/**
* 验证码图片的宽度,一般的,宽度应该是高度乘以字符数目
*/
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
/**
* 验证码图片的高度
*/
public void setHeight(int height) {
this.height = height;
}
public OutputStream getOutputStream() {
return outputStream;
}
/**
* 验证码输出地址,如果是在jsp或servlet里使用,这里的outputStream就是从Response对象里获取的outputStream
*/
public void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
public int getCharNumber() {
return charNumber;
}
/**
* 生成验证码的字符数量,默认四个
*/
public void setCharNumber(int charNumber) {
this.charNumber = charNumber;
}
public float getYawpRate() {
return yawpRate;
}
/**
* 设定噪声率,既图像上出现的噪声像素占全部像素的比例
* @param yawpRate
*/
public void setYawpRate(float yawpRate) {
this.yawpRate = yawpRate;
}
public static void main(String[] args) {
VerifyCodeASNI vs = new VerifyCodeASNI();
char[] codes = new char[4];
for (int i = 0; i < 4; i++) {
codes[i] = vs.getRandomChar();
}
char[] code2 = new char[9];
List list = new ArrayList();
while (true) {
// code2[i] = vs.getRandomChar();
Random random = new Random();
int de = random.nextInt(9);
if(list.size()>3){
break;
}
if(list.indexOf(de)<0){
list.add(de);
}
System.out.println(list.toString());
}
for (int i = 0; i < list.size(); i++) {
code2[list.get(i)]=codes[i];
}
for (int i = 0; i < code2.length; i++) {
String date = String.valueOf(code2[i]).trim();
if("".equals(date)){
code2[i] = vs.getRandomChar();
}
}
System.out.println(codes);
System.out.println(code2);
}
private void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
}
package com.shancai.controller.rand;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class RandCodeServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
{
processRequest(request, response);
}
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("image/jpeg");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0L);
HttpSession session = request.getSession(true);
//生成随机字串
String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
//生成图片
// int width = 100; int height = 40;
// VerifyCodeUtils.outputImage(width, height, response.getOutputStream(), verifyCode);
// String sid = request.getParameter("sid");
// if (sid == null) {
// sid = "rand";
// }
// session.setAttribute(sid, verifyCode);
//
int height =180;//验证码图片高度
int width = 150;//验证码图片宽度
VerifyCodeASNI vc = new VerifyCodeASNI(width, height);
vc.setCharNumber(4);
vc.setOutputStream(response.getOutputStream());
vc.write();
System.out.println(vc.getVerifyCode());
session.setAttribute("VerifyCode", vc.getVerifyCode());
}
}