Return an Image From JSP Page : Image Creation « JSP « Java Tutorial






index.html

<HTML>
    <HEAD>
        <TITLE>Creating Images on the Fly</TITLE>
    </HEAD>

    <BODY>
        <H1>Creating Images on the Fly</H1>
        <IMG SRC="basic.jsp">
    </BODY>
</HTML>

basic.jsp

<%@ page contentType="image/jpeg" import="java.io.*, java.awt.*, java.awt.image.*,com.sun.image.codec.jpeg.*" %>
<%
    try {
      BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
      Graphics2D g = image.createGraphics();

      g.setColor(Color.white);
      g.fillRect(0, 0, 199, 199);

      g.setColor(Color.blue);

      for(int i = 0; i < 20; i++){
          g.drawLine(0, i * 10, 199, i * 10);
          g.drawLine(i * 10, 0, i * 10, 199);
      }

      g.setColor(Color.red);

      g.drawLine(0, 129, 50, 119);
      g.drawLine(40, 119, 90, 150);
      g.drawLine(90, 10, 150, 60);
      g.drawLine(150, 30, 180, 90);
      g.drawLine(180, 90, 199, 50);

      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
      encoder.encode(image);

    } catch (Exception e) {
      
    }
%>
  Download:  JSPReturnImageFromJSPPage.zip( 1 k)








23.44.Image Creation
23.44.1.Generate JPEG image in jsp code
23.44.2.Use passed in parameter to draw a JPEG image
23.44.3.Return an Image From JSP Page