做了一个登陆验证码的生成小程序,或许对大家有用。支持背景图和文字旋转
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* Servlet implementation class for Servlet: ImageGenerator
*
*/
public class ImageGenerator extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("image/jpeg"); // 必须设置ContentType为image/jpeg
int length = 4; // 设置默认生成4个数字
Date d = new Date();
long lseed = d.getTime();
Random r = new Random(lseed); // 设置随机种子
if (request.getParameter("length") != null) {
try {
length = Integer.parseInt(request.getParameter("length"));
} catch (NumberFormatException e) {
}
}
// 可以在此加入保存验证码的代码
// 创建内存图像
BufferedImage bi = ImageIO.read(new File(this.getServletContext().getRealPath("./imgc.jpg")));
//可以在上面读入一个背景图,然后在背景图上写数字
Graphics2D g = bi.createGraphics();
g.setColor(Color.CYAN);
g.setFont(new Font(null, Font.BOLD, 15));
//旋转
double rot;
for (int i = 0; i < length; i++) {
g.drawString(String.valueOf(r.nextInt(9)), bi.getWidth()/4 + i * 15, bi.getHeight()/2);
rot = r.nextDouble() * 0.1;
if(r.nextBoolean())
rot = -1 * rot;
g.rotate(rot);
}
try {
// 使用JPEG编码,输出到response的输出流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response
.getOutputStream());
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
param.setQuality(1.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(bi);
} catch (Exception ex) {
}
}
}
自己配置一下背景图片的位置就可以了
@2008 杨一. 版权所有. 保留所有权利