JSP技巧:发送动态图像_PHP

WBOY
Release: 2016-06-01 12:35:00
Original
984 people have browsed it

页面(或者servlet)中发送动态产生的图像?这篇技巧告诉你如何做。要运行这里的代码,你需要一个Tomcat或者其他支持JSP 1.1的web服务器。

  当一个web页面带有image/jpeg (或者其他的图像格式)的MIME类型被发送时,你的浏览器将那个返回结果当作一个图像,然后浏览器显示图像,作为页面的一部分或者完全作为图像自身。要为你的jsp页面设置MIME类型,你需要设置页面的contentType属性:
  

  然后你需要创建一个BufferedImage绘制你的动态图像:
  BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

  创建完一个BufferedImage后,你需要得到图形环境进行绘制,一个Graphics或者Graphics2D对象:

  Graphics g = image.getGraphics();
  // or
  Graphics2d g2d = image.createGraphics();

   从现在起你就可以绘制图像内容了。对图形环境绘制就会画到BufferedImage。最开始这个图像都是黑色的,因此用你希望的背景颜色填充图像是一个不错的主意,然后,当你完成图像的绘制,你需要dispose图形环境:

  g.dispose();
  // or
  g2d.dispose();


 一旦完成图像的绘制,你在response中返回那个图像。你可以使用非标准的com.sun.image.codec.jpeg包中的JPEGImageEncoder类编码图像,或者如果你使用JDK1.4,你可以使用标准的ImageIO类。在使用JPEGImageEncoder时有一个技巧,你必须从ServletResponse取来ServletOutputStream而不能使用隐含的JSP输出变量out。

  ServletOutputStream sos = response.getOutputStream();
  JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
  encoder.encode(image);
  // or
  ImageIO.write(image, "JPEG", out);

  这里有一个从所有的可能方案中(例如g.dispose();或者g2d.dispose();)选取的一个完整的范例.这个例子使用Graphics对象绘制一个随机的多边形,图像通过JPEGImageEncoder绘制,你可以自由设置多边形的顶点数得到更复杂的形状,换言之,有更多顶点和边。

  要运行这个范例,将从""之间的jsp代码放到一个名为image.jsp的文件中,将那个文件放到你的web服务器可以找到的地方,在使用Tomcat的情况下是ROOT目录,启动Tomcat,访问http://localhost:8080/image.jsp
   import="java.awt.*,java.awt.image.*,
  com.sun.image.codec.jpeg.*,java.util.*"
  %>  
    // Create image
  int width=200, height=200;
  BufferedImage image = new BufferedImage(width,
  height, BufferedImage.TYPE_INT_RGB);
  // Get drawing context  (代码实验室)
  Graphics g = image.getGraphics();
  // Fill background
  g.setColor(Color.white);
  g.fillRect(0, 0, width, height);
  // Create random polygon
  Polygon poly = new Polygon();
  Random random = new Random();
  for (int i=0; i < 5; i++) {
  poly.addPoint(random.nextInt(width),
  random.nextInt(height));
  }
  // Fill polygon
  g.setColor(Color.cyan);
  g.fillPolygon(poly);
  // Dispose context
  g.dispose();
  // Send back image
  ServletOutputStream sos = response.getOutputStream();
  JPEGImageEncoder encoder =
  JPEGCodec.createJPEGEncoder(sos);
  encoder.encode(image);
  %> (代码实验室)

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!