package jimmee.cn.edu.zju; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyImage extends HttpServlet ...{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ...{ /** *//************************************************************************** * 创建一个Bufferedimage对象:通过调用BufferedImage的构造函数,给出宽度、高度 * 以及由BufferedImage类中定义的常量所定义的图像表示类型,从而我们创建了一个 * java.awt.image.BufferedImage对象。表示类型并不重要,因为我们并不直接操纵 * BufferedImage中的二进制位,而且在转换到JPEG时大多数类型都产生相同的结果。我们 * 这里使用TYPE_INT_RGB。 ***************************************************************************/ int width = 320, height = 400; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); /** *//************************************************************************** * 通过调用图像的getGraphics方法,将得到的Graphics对象转换成Graphics2D,然后使用 * Java 2D丰富的绘画操作,坐标变换,字体设置和填充调色板执行具体的绘画。 **************************************************************************/ Graphics2D g2d=(Graphics2D) image.getGraphics(); g2d.setColor(Color.YELLOW); g2d.fillRect(0, 0, width, height); // 定义渐进色 GradientPaint gp1 = new GradientPaint(15, 75, Color.RED, 50, 120, Color.GREEN, false); g2d.setPaint(gp1); g2d.fill(new Rectangle(50, 10, width-100, height-220)); GradientPaint gp2 = new GradientPaint(15, 75, Color.RED, 50, 120, Color.GREEN, true); g2d.setPaint(gp2); g2d.fill(new Rectangle(50, 210, width-100, height-220)); // 部署图形 g2d.dispose(); /** *//********************************************************************** * 设置Content-Type响应报头(设置MIME类型) **********************************************************************/ response.setContentType("image/jpeg"); //获得输出流 OutputStream out=response.getOutputStream(); //以JPEG格式将BufferedImage发送到输出流 ImageIO.write(image, "jpg", out); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ...{ doGet(request,response); } }