In Web applications, images are often generated dynamically, such as real-time stock market quotations and various statistical charts. In this case, images can only be dynamically generated in the server memory and sent to users, then it is displayed in the browser.
Essentially, when a browser requests a static image such as jpeg from the server, the server still returns a standard http response, except that the contentType of the http header is not text/html, but image/jpeg. Therefore, in Servlet, you only need to set the contentType and then send the data stream of the image. Then, the browser can correctly parse and display the image.
In Java, java. awt and java. awt. the image package provides basic image rendering capabilities. We can draw the desired image in the memory, encode the image into jpeg or other image formats, and then send it to the browser. The following describes how to dynamically create an image using Servlet:
1. Create a BufferedImage object, which exists in the memory and stores the drawn image;
2. Create a Graphics2D object, which is used to draw the desired image;
3.after the plotting is completed, the JPEG encoder of com.sun.image.codec.jpeg package is used to encode the image;
4. Finally, output the encoded data to HttpResponse.
The embedded com.sun.image.codec.jpeg package is located in the rt. jar package in the JDK directory. It is not a public API and you need to copy rt. jar to the WEB-INF/lib of the web application.
First, create the simplest Servlet:
Public class CreateImageServlet extends HttpServlet {
Protected void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException
{
Response. setContentType ("image/jpeg ");
}
}
First, we set the contentType of response to image/jpeg, so that the browser can correctly identify it.
Create a BufferedImage object of x and prepare the drawing:
Int width = 100;
Int height = 100;
BufferedImage bi = new BufferedImage (width, height, BufferedImage. TYPE_INT_RGB );
Next, obtain the Graphics2D object in the BufferedImage object and draw the drawing:
Graphics2D g = bi. createGraphics (); // create a Graphics2D object
// Fill the background in White: