以下 servlet 在内存中生成图像,然后编码成 jpeg, 并输出到servlet的输出流.
(如果需要 gif 格式,则可以用一个 gif 编码类.)
调用 这个 servlet 的方法:
<img src=http://yourserver/servlet/servletjpeg?str=hi>
// filename: servletjpeg.java
// This is a simple Java servlet which can generate jpeg image.
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.sun.image.codec.jpeg.*;
public class servletjpeg extends HttpServlet{
public voiddo
Get(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String str = req.getParameter("str");
Frame frame = new Frame();
frame.addNotify();
frame.setBackground(new Color(255,212,212));
BufferedImage image = (BufferedImage) frame.createImage(200, 100);
Graphics g= image.getGraphics();
g.drawString(str, 50, 50);
res.setContentType("image/jpeg");
ServletOutputStream out = res.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
}
public voiddo
Post(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
do
Get(req,res);
}
}