图片验证码生成

时间:2023-02-09 22:05:51

代码地址:点击打开链接

package util.image;

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

import javax.imageio.ImageIO;

/**
* to buide image
* @author 沈健
*
*/
public class ImageVertifyUtil {

/*
* 字典符
*/
private static final char[] CHARS={'2','3','4','5','6','7','8','9','0',
'A','B','C','D','E','F','G','H','J','K','L','M',
'N','P','Q','R','S','T','U','V','W','X','Y','Z'};//除去不容易辨认的字符

private static Random random=new Random();//获取随机数

private static String getRandomString(){//生成6位随机验证码
StringBuffer buffer=new StringBuffer();
for(int i=0;i<6;i++){
buffer.append(CHARS[random.nextInt(CHARS.length)]);
}
return buffer.toString();
}

private static Color getRandomColor(){//获取随机的颜色
return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
}

private static Color getReverseColor(Color color){//获取某颜色的反色
return new Color(255-color.getRed(),255-color.getGreen(),255-color.getBlue());
}


/**
* 返回生成的字符串
*/
public static String buildImage(OutputStream os){

final int width=100;
final int height=30;

BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//创建一个彩色图片

Graphics2D g=bi.createGraphics();//获取彩色对象

g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16));

Color color=getRandomColor();
g.setColor(color);
g.fillRect(0, 0, width, height);

g.setColor(getReverseColor(color));

String string=getRandomString();//生成的字符
g.drawString(string, 18, 20);

for(int i=0,n=random.nextInt(100);i<n;i++){//画最多100个噪音点
g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
}

g.dispose();

try {
ImageIO.write(bi, "jpg",os);
} catch (IOException e) {
e.printStackTrace();
}

return string;
}
}

测试类:
package util.image.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.junit.Test;

import util.image.ImageVertifyUtil;

public class ImageVertifyUtilTest {

@Test
public void testImageVertifyUtil() throws IOException{
OutputStream os=new FileOutputStream("d:\\a.jpg");
ImageVertifyUtil.buildImage(os);
os.close();
}
}