Example of dynamic JPEG Image Generation by Servlet

Source: Internet
Author: User

// GenerateImage. java
/* Example of dynamically generating JPEG images */
Import java. awt .*;
Import java. awt. image .*;
Import com.sun.image.codec.jpeg. *; // encoding class
Java. util .*;
Javax. servlet .*;
Javax. servlet. http .*;
Java. io .*;


Class GenerateImage extends HttpServlet
Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, java. io. IOException {

Response. setContentType ("image/jpeg "):
Int width = 200, height = 200;
BufferedImage image = BufferedImage (width, height, BufferedImage. TYPE_INT_RGB );
Graphics g = image. getGraphics ();
G. setColor (Color. white );
G. fillRect (0, 0, width, heitht );
Polygon poly = new Polygon ();
Random random = new Random ();
For (int I = 0; I <5; I ++)
{
Poly. addPoint (random. nextInt (width), random. nextInt (height ));
}
G. setColor (Color. cyan );
G. fillPolygon (poly );
G. dispose (); // The image is not shashed by Graphics.

ServletOutputStream sos = response. getOutputStream (); // binary
Required imageencoder encoder = required codec. createJPEGEncoder (sos); // create an encoder and output it to sos.
Encoder. encode (image );
}

Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, java. io. IOException {
DoGet (request, response );
}

}

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.