Send dynamically generated images in a page (or servlet)? This tip tells you how to do it. To run the code here, you need a tomcat or other Web server that supports JSP 1.1.
When a MIME type of a Web page with image/jpeg (or other image format) is sent, your browser treats the return result as an image, and then the browser displays the image as part of the page or as the image itself. To set the MIME type for your JSP page, you need to set the ContentType property of the page:
-->
Then you need to create a bufferedimage to draw your dynamic image:
BufferedImage image = new BufferedImage (width, height, bufferedimage.type_int_rgb);
After creating a bufferedimage, you need to get a graphical environment to draw, a graphics or Graphics2D object:
Graphics g = image.getgraphics ();
Or
Graphics2D g2d = Image.creategraphics ();
From now on you can draw the image content. Drawing to the graphics environment will be drawn to the bufferedimage. This image is all black at first, so it's a good idea to fill the image with the background color you want, and then, when you finish drawing the image, you need the Dispose graphics environment:
G.dispose ();
Or
G2d.dispose ();
Once you have finished drawing the image, you return that image in the response. You can use the JPEGImageEncoder class in non-standard com.sun.image.codec.jpeg packages to encode images, or if you use JDK1.4, you can use the standard ImageIO class. There is a trick in using jpegimageencoder that you have to take from Servletresponse to Servletoutputstream instead of using an implied JSP output variable out.
Servletoutputstream SOS = Response.getoutputstream ();
JPEGImageEncoder encoder = Jpegcodec.createjpegencoder (SOS);
Encoder.encode (image);
Or
Imageio.write (Image, "JPEG", out);
Here is one from all possible schemes (e.g. g.dispose (); or g2d.dispose ();) Select a complete example. This example uses the Graphics object to draw a random polygon, the image is drawn by JPEGImageEncoder, and you can freely set the vertices of the polygon to get more complex shapes, in other words, have more vertices and edges.
To run this example, you will start from the -->"Between the JSP code in a file named image.jsp, put that file where your Web server can be found, in the case of Tomcat is the root directory, start Tomcat, Access http://localhost:8080/image.jsp
<%@ page contenttype= "Image/jpeg"
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.