import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 动态生成图片
*
* @author fixed
*
*/
public class DynamicImageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setCharacterEncoding("GBK");
//设置响应类型(图片)
response.setContentType("image/jpeg");
//随机生成一位数字
int ranInt = (int)(Math.random()*10);
//随机生成个字母
char ranChar = (char)(\'a\'+Math.random()*(\'z\'-\'a\'+1));
//随机字符串
String ranStr = ranInt+" "+ranChar;
//创建图象
int width = 50;
int height = 30;
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//得到图片上下文
Graphics2D g = (Graphics2D)image.getGraphics();
//填充背景
g.setColor(Color.gray);
g.fillRect(0, 0, width, height);
//画字符串
g.setColor(Color.white);
g.setFont(new Font("Dialog",Font.PLAIN,14));
g.drawString(ranStr, 10, height/2+4);
//画边框
g.setColor(Color.black);
g.drawRect(0, 0, width-1, height-1);
g.dispose();
ServletOutputStream sos = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
encoder.encode(image);
}
}