How to use the Java servlet to dynamically generate pictures

Source: Internet
Author: User
Tags object flush set background server memory
Servlet| Dynamic | Detailed in the Web application, often need to dynamically generate pictures, such as real-time stock quotes, various statistical charts, etc., in this case, the picture can only be dynamically generated in the server memory and sent to the user, and then displayed in the browser.

Essentially, when a browser requests a static picture such as JPEG from the server, the server returns the standard HTTP response, except that the contenttype of the HTTP header is not text/html but image/jpeg, so As long as we set the ContentType in the servlet and send the image data stream, the browser can parse and display the picture correctly.

In Java, the java.awt and java.awt.image packages provide the basic ability to draw images, we can draw the desired graphics in memory, then encode them into JPEG or other image formats, and finally send the corresponding browser. The following are detailed steps for creating images dynamically using a servlet:

1. Creates a BufferedImage object that exists in memory and is responsible for saving the drawn image;

2. Creates a Graphics2D object that is responsible for drawing the desired image;

3. When the drawing is finished, the JPEG encoder that calls the COM.SUN.IMAGE.CODEC.JPEG packet is encoded;

4. Finally, the encoded data output to HttpResponse can be.

Note that the Com.sun.image.codec.jpeg package is in the Rt.jar package in the JDK directory and is not a public API and needs to be replicated Rt.jar to the web-inf/lib of the Web application.

Let's first create the simplest servlet:

       
        
         
        public class Createimageservlet extends HttpServlet {protected void doget (HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {response.setcontenttype ("Image/jpeg");}
       
        


We first set the response contenttype as Image/jpeg so that the browser can recognize it correctly. Then, create a BufferedImage object of size 100x100 to prepare the drawing:

       
        
         
        int width = 100;int height = 100; BufferedImage bi = new BufferedImage (width, height, bufferedimage.type_int_rgb);
       
        


Next, get the Graphics2D object in the BufferedImage object and draw:

       
        
         
        Graphics2D g = bi.creategraphics ()///Create Graphics2D object//Fill background is white: G.setbackground (Color.Blue); g.clearrect (0, 0, width, Height)//Set foreground color: G.setcolor (color.red);/start drawing: G.drawline (0, 0, 99, 99);//Draw a line//drawing complete, Release resources: G.dispose (); Bi.flush ();
       
        


Then, the bufferedimage is JPEG encoded:

       
        
         
        JPEGImageEncoder encoder= Jpegcodec.createjpegencoder (out); JPEGEncodeParam param = encoder.getdefaultjpegencodeparam (bi);p aram.setquality (1.0f, false); Encoder.setjpegencodeparam (param); try{encoder.encode (BI);} catch (IOException IoE) {ioe.printstacktrace ();}
       
        


The encoded JPEG image is exported directly to the out object, and we just pass in the response. Getoutputstream () can be directly exported to the HttpResponse.

Here's the complete code:

       
        
Package Com.crackj2ee.web.util;import Java.io.*;import java.awt.*;import java.awt.image.*;import javax.servlet.*; Import javax.servlet.http.*;import com.sun.image.codec.jpeg.*;/*** @author Liao xue Feng*/public class Createimageservlet extends httpservlet{protected void doget (HttpServletRequest request, httpservletresponse response)  Throws Servletexception,ioexception {response.setcontenttype ("image/jpeg"); CreateImage (Response.getoutputstream ());  private void CreateImage (OutputStream out) {int width = 100;  int height = 100;  BufferedImage bi = new BufferedImage (width, height, bufferedimage.type_int_rgb);  Graphics2D g = bi.creategraphics ();  Set Background:g.setbackground (Color.Blue);  G.clearrect (0, 0, width, height);  Set Fore Color:g.setcolor (color.red);  Start Draw:g.drawline (0, 0, 99, 199);  End Draw:g.dispose ();  Bi.flush ();  Encode:jpegimageencoder encoder = Jpegcodec.createjpegencoder (out); JPEGEncodeParam param = ENCODER.GETDEFAULTJPEGENCODEPAram (BI);  Param.setquality (1.0f, false);  Encoder.setjpegencodeparam (param);  try {encoder.encode (BI);  catch (IOException IoE) {ioe.printstacktrace (); } }}
       


Finally compile the servlet, register it into web.xml, map the path to/createimage, and write a simple index.html test:

       
        
            
           
       
        


If you can show it correctly, you're done.

Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.