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();
}
}
}
最后将这个Servlet编译,注册到web.xml中,映射路径为/CreateImage,写一个简单的index.html测试:
<html><head></head>
<body>
<img src="CreateImage">
</body></html>