要动态产生图片其实很简单,直接看一个Servlet实现的例子:
package onlyfun.caterpillar; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; 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 ImageShower extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("image/jpeg"); BufferedImage bufferedImage = new BufferedImage(300, 200, BufferedImage.TYPE_INT_RGB); Graphics g = bufferedImage.getGraphics(); g.setColor(Color.white); g.setFont(new Font("Arial Black", Font.ITALIC | Font.BOLD, 20)); g.drawString("caterpillar.onlyfun.net", 20, 20); g.setColor(Color.red); g.fillOval(40, 40, 20, 20); g.setColor(Color.green); g.fillRect(80, 80, 50, 50); OutputStream out = res.getOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(bufferedImage); out.close(); } }
图片的成果如下:
|