package com.xh.util;
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 MakeCode extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//禁止浏览器缓存随见图片
response.setDateHeader("Expires", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
//通知浏览机以图片的方式打开传递过去的数据
response.setHeader("Content-Type", "image/jpeg");
//在内存中穿件一副图片 BufferedImage(int width, int height, int imageType)
BufferedImage image = new BufferedImage(80, 30,BufferedImage.TYPE_INT_RGB);;
//向图片写数据 得到相应的画笔
Graphics g = image.getGraphics();
//设置背景色
g.setColor(Color.WHITE);
//fillRect(int x, int y, int width, int height) 填充指定的矩形。
g.fillRect(0, 0, 80, 30);
//设置写入数据的颜色和字体
g.setColor(Color.BLACK);
g.setFont(new Font(null, Font.BOLD, 20));
//想图片上写数据
String num=makeNum();
//将随即产生的数值保存到session中去
request.getSession().setAttribute("checked", num);
g.drawString(num, 0, 20);
//把写好的数据的图片输出给浏览器
ImageIO.write(image, "jpg", response.getOutputStream());
}
private String makeNum() {
Random r=new Random();
String num=r.nextInt(9999999)+"";
StringBuffer sb=new StringBuffer();
for(int i=0;i<7-num.length();i++){
sb.append("0");
}
num=sb.toString()+num;
return num;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
在页面里:<img src="servleturl" />