//GenerateImage.java
/* 動態產生JPEG圖像的例子 */
import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*; //編碼類
java.util.*;
javax.servlet.*;
javax.servlet.http.*;
java.io.*;
class GenerateImage extends HttpServlet
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, java.io.IOException {
response.setContentType("image/jpeg"):
int width=200, height=200;
BufferedImage image = BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.white);
g.fillRect(0,0,width,heitht);
Polygon poly = new Polygon();
Random random = new Random();
for(int i=0;i<5;i++)
{
poly.addPoint(random.nextInt(width),random.nextInt(height));
}
g.setColor(Color.cyan);
g.fillPolygon(poly);
g.dispose(); //消拙Graphics 對圖形沒有肖毀
ServletOutputStream sos =response.getOutputStream(); //二進制
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos); //創建編碼器,輸出到sos那裡
encoder.encode(image);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, java.io.IOException {
doGet(request,response);
}
}