1、代码
package image;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
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 ImageCheck extends HttpServlet{
final private int WIDTH=60;//图片的宽
final private int HEIGHT=30;//图片的高
final private int CHECKNUMLENGTH=4;//验证码长度
final private int LINENUM=15;//随即线条数量
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获得图片流
BufferedImage bi=new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
//给图片加画笔
Graphics g=bi.getGraphics();
//画边框
g.setColor(Color.white);//背景颜色
g.fillRect(1, 1, WIDTH-2, HEIGHT-2);//边框
//g.drawRect(0, 0, WIDTH, HEIGHT);
//改变字体大小
g.setFont(new Font(null, Font.BOLD, 20));
//获得随机数
String str=random();
//给图片加上文字
g.setColor(Color.blue);
g.drawString(str, 10,22);
//给图片加上随即线条
drawRandomLine(g);
//把文字存储在session中
HttpSession session = req.getSession();
session.setAttribute("random", str);
ImageIO.write(bi, "jpg", resp.getOutputStream());
}
/**
* 生成随机字符串(数字加字母)
*/
private String random() {
//随机字符生成四位
Random r=new Random();
char[] random="1234567890abcdefghijklmopqrstuvwxyz".toCharArray();
StringBuffer checkstr=new StringBuffer();
for(int i=0;i<CHECKNUMLENGTH;i++){
int index=r.nextInt(random.length);
checkstr.append(random[index]);
}
return checkstr.toString();
}
/**
* 在图片上画随机线条
* @param g
*/
private void drawRandomLine(Graphics g) {
// 设置颜色
g.setColor(Color.red);
// 设置线条个数并画线
for (int i = 0; i < LINENUM; i++) {
int x1 = new Random().nextInt(WIDTH);
int y1 = new Random().nextInt(HEIGHT);
int x2 = new Random().nextInt(WIDTH);
int y2 = new Random().nextInt(HEIGHT);
g.drawLine(x1, y1, x2, y2);
}
}
}
2、演示图片