package cn.it.web.controller;
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;
public class ImageServlet extends HttpServlet {
int width = 80;
int height = 20;
char[] buf = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ".toCharArray();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 填充背景
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 画框
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
// 写字符
g.setColor(Color.BLUE);
g.setFont(new Font("粗体", Font.BOLD, 15));
Random r = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
int pos = r.nextInt(buf.length);
char c = buf[pos];
sb.append(c);
g.drawString(String.valueOf(c), (i * 2 + 1) * (width / 9), 15);
}
String code = sb.toString();
// 将验证码存入session
req.getSession().setAttribute("code", code);
ImageIO.write(image, "jpeg", resp.getOutputStream());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}