Have you ever wanted to send a dynamically generated image from a JSP 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:
<table cellSpacing=0 borderColorDark=#ffffff cellPadding=2 width=400 align=center borderColorLight=black border=1>
<tr> <td class=code style="FONT-SIZE: 9pt" bgColor=#e6e6e6>
Graphics g = image.getGraphics();
// or
Graphics2d g2d = image.createGraphics();</td></tr>
</table>
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:
<table cellSpacing=0 borderColorDark=#ffffff cellPadding=2 width=400 align=center borderColorLight=black border=1>
<tr> <td class=code style="FONT-SIZE: 9pt" bgColor=#e6e6e6>
g.dispose();
// or
g2d.dispose();</td></tr>
</table>
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.
<table cellSpacing=0 borderColorDark=#ffffff cellPadding=2 width=400 align=center borderColorLight=black border=1>
<tr> <td class=code style="FONT-SIZE: 9pt" bgColor=#e6e6e6>
ServletOutputStream sos = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
encoder.encode(image);
// or
ImageIO.write(image, "JPEG", out);</td></tr>
</table>