This example shows how we can dynamically create an image from a text ('Hello World!') by writing a simple Java Servlet. In the next post, we'll see how this dynamic creation of image can be used to implement custom CAPTCHA validation.

Tools and Technologies used in this article

  1. JSP / Servlet
  2. Eclipse 3.7
  3. Tomcat 7
  4. JDK 1.6

1. Create Dynamic Web Project

Select from the menu File --> New --> Dynamic Web Project (say 'ImageCreatorServlet').

2. Write a Java Servlet

Create a servlet class (say com.srccodes.examples.servlet.ImageCreator)
Modify the java class as per the following code.
File: ImageCreator.java

package com.srccodes.examples.servlet;
 
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.sun.image.codec.jpeg.JPEGCodec;
 
/**
 * @author Abhijit Ghosh
 * @version 1.0
 */
public class ImageCreator extends HttpServlet {
    private static final long serialVersionUID = -1761346889117186607L;
 
    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // set mime type as jpg image
        response.setContentType("image/jpg");
        ServletOutputStream out = response.getOutputStream();
 
        BufferedImage image = new BufferedImage(200, 40, BufferedImage.TYPE_BYTE_INDEXED);
 
        Graphics2D graphics = image.createGraphics();
         
        // Set back ground of the generated image to white
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, 200, 40);
 
        // set gradient font of text to be converted to image
        GradientPaint gradientPaint = new GradientPaint(10, 5, Color.BLUE, 20, 10, Color.LIGHT_GRAY, true);
        graphics.setPaint(gradientPaint);
        Font font = new Font("Comic Sans MS", Font.BOLD, 30);
        graphics.setFont(font);
 
        // write 'Hello World!' string in the image
        graphics.drawString("Hello World!", 5, 30);
 
        // release resources used by graphics context
        graphics.dispose();
 
        // encode the image as a JPEG data stream and write the same to servlet output stream   
        JPEGCodec.createJPEGEncoder(out).encode(image);
 
        // close the stream
        out.close();
    }
}

3. Add servlet mapping

Add servlet mapping for the servlet ImageCreator in web.xml.
File: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>ImageCreatorServlet</display-name>
    <servlet>
        <description>
        </description>
        <display-name>ImageCreator</display-name>
        <servlet-name>ImageCreator</servlet-name>
        <servlet-class>com.srccodes.examples.servlet.ImageCreator</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ImageCreator</servlet-name>
        <url-pattern>/ic.jpg</url-pattern>
    </servlet-mapping>
</web-app>

4. Create a Jsp page

Create a jsp page (say test.jsp) and add a html tag to display the dynamically generated image.
File: test.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Dynamic Image</title>
</head>
<body>
    <img alt="my Image" src="ic.jpg">
</body>
</html>

5. Overall Project Structure

Overall Project Structure

6. Run Your Code

Right click on 'test.jsp' and select from context menu 'Run As' --> 'Run on Server'.

7. Browser Output

Eclipse will open a browser and an image of 'Hello World!' will be shown in the browser.
Browser Output

Download SrcCodes

All code samples shown in this post are available in the following link ImageCreatorServlet.zip

References