Use Java Servlet to dynamically generate images

Source: Internet
Author: User
Tags server memory
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:
G. setbackground (color. Blue );
G. clearrect (0, 0, width, height );
// Set the foreground color:
G. setcolor (color. Red );
// Start plotting:
G. drawline (0, 0, 99, 99); // draw a straight line
// After drawing is completed, release the resource:
G. Dispose ();
Bi. Flush ();

Then, perform JPEG encoding on bufferedimage:


Required imageencoder encoder = required codec. createjpegencoder (out );
Export encodeparam Param = encoder. getdefaultjpegencodeparam (BI );
Param. setquality (1.0f, false );
Encoder. setincluencodeparam (PARAM );
Try {
Encoder. encode (BI );
}
Catch (ioexception IOE ){
IOE. printstacktrace ();
}

After the encoded JPEG image is directly output to the out object, we only need to input response. getoutputstream () to directly output it to httpresponse.

The complete code is as follows:


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:
Required imageencoder encoder = required codec. createjpegencoder (out );
Export encodeparam Param = encoder. getdefaultjpegencodeparam (BI );
Param. setquality (1.0f, false );
Encoder. setincluencodeparam (PARAM );
Try {
Encoder. encode (BI );
}
Catch (ioexception IOE ){
IOE. printstacktrace ();
}
}
}

Finally, compile the servlet and register it to Web. xml. The ing path is/createimage, and write a simple index.html test:


<HTML> <Body>

</Body>

If it can be correctly displayed, you are done!

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.