www.pudn.com > bookshop.zip > ImgServlet.java, change:2013-07-08,size:1633b


package com.tarena.web; 
 
import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.image.BufferedImage; 
import java.io.IOException; 
import java.io.OutputStream; 
import java.io.PrintWriter; 
import java.util.Random; 
 
import javax.jms.Session; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.HttpSession; 
 
import com.sun.image.codec.jpeg.JPEGCodec; 
import com.sun.image.codec.jpeg.JPEGImageEncoder; 
 
public class ImgServlet extends HttpServlet { 
 
	public void service(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException { 
		response.setContentType("imag/JPEG"); 
		int width = 60, height = 20; 
		 BufferedImage image = new BufferedImage(width, height,    
		            BufferedImage.TYPE_INT_RGB);    
		 // 获取图形上下文    
		    Graphics g = image.getGraphics();    
		    //生成随机类    
		   Random random = new Random();    
		    // 设定背景色    
		    g.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));    
		    g.fillRect(0, 0, width, height);    
 
		    //画边框    
		    g.setColor(new Color(0,0,0));    
		    String number=Integer.toString(random.nextInt(99999)); 
			g.drawString(number, 10, 15); 
			 
			HttpSession session = request.getSession(); 
			session.setAttribute("number",number); 
			 
			OutputStream os=response.getOutputStream(); 
			JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(os);//压缩格式 
			encoder.encode(image); 
	} 
 
}