天天看點

動态生成圖檔sevlet

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);
    }
}