随笔-13  评论-12  文章-3  trackbacks-0
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.servlet.ServletException;
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;

public class ImageServlet extends HttpServlet {

    
public void service(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException, IOException {
        
// 设置响应类型
        response.setContentType("image/jpeg");
        
// 图片的内存映像
        BufferedImage image = new BufferedImage(5020,BufferedImage.TYPE_INT_RGB);
        
// 获得画笔对象
        Random r = new Random();
        Graphics g 
= image.getGraphics();
        g.setColor(
new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
        g.fillRect(
005020);
        g.setColor(
new Color(0,0,0));
        String number 
= String.valueOf(r.nextInt(99999)); 
        g.drawString(number, 
515);

        
// 压缩成jpeg格式
        OutputStream os = response.getOutputStream();

        JPEGImageEncoder encoder 
= JPEGCodec.createJPEGEncoder(os);

        
// 把BufferedImage对象中的图像信息编码后
        
// 向创建该对象(encoder)时指定的输出流输出
        encoder.encode(image);
        
    }

}
posted on 2010-11-21 12:46 zeroline 阅读(572) 评论(0)  编辑  收藏 所属分类: Servlet/JSP

只有注册用户登录后才能发表评论。


网站导航: