图形验证码的java通用类(二)
s IOException
*/
public String drawAlpha(String graphicFormat,OutputStream out) throws IOException{
// 随机生成的串的值
String charValue = "";
charValue = randAlpha();
return draw(charValue,graphicFormat,out);
}
/**
* 以图像方式绘制字符串,绘制结果输出到流out中
* @param charValue 要绘制的字符串
* @param graphicFormat 设置生成的图像格式,值为GRAPHIC_JPEG或GRAPHIC_PNG
* @param out 图像结果输出流
* @return 随机生成的串的值
* @throws IOException
*/
protected String draw(String charValue,String graphicFormat,OutputStream out) throws IOException{
//计算图像的宽度和高度
int w = (charCount+2) * wordWidth;
int h = wordHeight * 3;
//创建内存图像区
BufferedImage bi = new BufferedImage(w,h,BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = bi.createGraphics();
//设置背景色
Color backColor = Color.WHITE;
g.setBackground(backColor);
g.fillRect(0,0,w,h);
//设置font
g.setFont(new Font(null,Font.BOLD,fontSize));
//绘制charValue,每个字符颜色随机
for(int i = 0; i < charCount; i++){
String c = charValue.substring(i,i+1);
Color color = CHAR_COLOR[randomInt(0,CHAR_COLOR.length)];
g.setColor(color);
int xpos = (i+1) * wordWidth;
//垂直方向上随机
int ypos = randomInt(initypos+wordHeight,initypos+wordHeight*2);
g.drawString(c,xpos,ypos);
}
g.dispose();
bi.flush();
// 输出到流
ImageIO.write(bi,graphicFormat,out);
return charValue;
}
protected String randNumber(){
String charValue = "";
//生成随机数字串
for (int i = 0; i < charCount; i++){
charValue += String.valueOf(randomInt(0,10));
}
return charValue;
}
String charValue = "";
//生成随机字母串
for (int i = 0; i < charCount; i++){
char c = (char) (randomInt(0,26)+'a');
charValue += String.valueOf(c);
}
return charValue;
}
/**
* 返回[from,to)之间的一个随机整数
*
* @param from 起始值
* @param to 结束值
* @return [from,to)之间的一个随机整数
*/
protected int randomInt(int from,int to){
//Random r = new Random();
return from+r.nextInt(to-from);
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
System.out.println(RandomGraphic.createInstance(5).drawAlpha(RandomGraphic.GRAPHIC_PNG,new FileOutputStream("c:/myimg.png")));
}
}
RandomGraphic类原代码结束
在servlet中使用该类,将图片输出到客户端,在页面上就可显示随机图片
package net;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RandImage extends HttpServlet {
public RandImage() {
super();
}
protected void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException{
//设置输出内容为图像,格式为jpeg
res.setContentType("image/jpg");
try {
//将内容输出到响应客户端对象的输出流中,生成的图片中包含6个字符
String v = RandomGraphic.createInstance(6).drawAlpha(RandomGraphic.GRAPHIC_JPEG,res.getOutputStream());
//将字符串的值保留在session中,便于和用户手工输入的验证码比较,比较部分不是本文讨论重点,故略
req.getSession().setAttribute("rv",