When the MIME type of a web page with image/jpeg or other image formats is sent, your browser treats the returned result as an image and then displays the image in the browser, as part of a page or as an image itself. To set the MIME type for your jsp page, you need to set the contentType attribute of the page:
<%@ page contentType="image/jpeg" ... %> |
Then you need to create a BufferedImage to draw your dynamic image:
BufferedImage image = new BufferedImagewidth,height, BufferedImage.TYPE_INT_RGB); |
After creating a BufferedImage, You need to obtain the graphic environment for drawing, a Graphics or Graphics2D object:
Graphics g = image.getGraphics); // or Graphics2d g2d = image.createGraphics); |
From now on, you can draw the image content. The image environment will be painted to BufferedImage. This image is black at first, so it is a good idea to fill the image with the background color you want. Then, when you complete the image painting, you need to dispose the graphic environment:
g.dispose); // or g2d.dispose); |
Once the image is drawn, you return the image in response. You can use the custom imageencoder class in the non-standard com.sun.image.codec.jpeg package to encode the image, or if you use JDK1.4, you can use the standard ImageIO class. There is a trick when using tranquility imageencoder. You must obtain ServletOutputStream from ServletResponse, instead of using the implied JSP output variable out.
ServletOutputStream sos = response.getOutputStream); JPEGImageEncoder encoder =JPEGCodec.createJPEGEncodersos); encoder.encodeimage); // or ImageIO.writeimage, "JPEG", out); |
Here there is an example from all possible solutions, such as g. dispose); or g2d. dispose);) Select a complete example. in this example, a random polygon is drawn using a Graphics object, and the image is drawn using JPEGImageEncoder. You can freely set the number of vertices of a polygon to get a more complex shape. In other words, there are more vertices and edges.
To run this example, place the jsp code from "<% @" to the last "%>" into an image. in the jsp file, place the file to a location that can be found on your web server. When Tomcat is used, it is the ROOT directory. start Tomcat and access http: // localhost: 8080/image. jsp.
Related Articles]
- JSP obtains the browser and operating system information of the client.
- Three methods to display Chinese Characters in Web programs developed by JSP
- Develop an Eclipse plug-in for debugging JSP