Servlet动态产生JPEG图像的例子
//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);
}
}