Dynamic image jsp
To create a dynamic jpg image "on the fly" using a jsp file.
<%@ page language="java" %><%
%><%@ page contentType="image/jpeg"%><%
%><%@ page import="com.sun.image.codec.jpeg.*"%><%
BufferedImage image= new BufferedImage(
200,
200,
BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
//create a rectangle filled with the color white:
g.setColor(Color.white);
g.fillRect(0,0,200,200);
//add some text
g.setColor(Color.black);
g.drawString("Hello world",20,20);
ServletOutputStream out1 = response.getOutputStream();
JPEGImageEncoder encoder= JPEGCodec.createJPEGEncoder(out1);
encoder.encode(image);
%>
When using a jsp file to draw an image you must control the outputstream.
Note that the import lines have %><% at the end of the line, if you end a line with %> and start the next line with <%, you'll actually get the tomcat motor to automatically do a out.println(), then the graphics will not have a "clean" outputstream.
Avoid any use of out.println(""); and for example <%= debugString %> in this code. This will only get you the error "outputstream already commited". Also be aware that the first and last characters in the jsp file must be a <% and %>, any characters (whitespace included) will "clutter" the outputstream.
Notice content type, it's important that you use the right content type for for the file that you are serving.
<%@ page contentType="image/jpeg"%>
To display your new dynamic jsp image you can use this html code.
<img src="myDynamicImage.jsp" alt="Dyniamic Image jsp"/>