Lucky Dip Logo
Powered by PlusNet. PlusNet broadband.
Patrick's Lucky Dip
Home > Java > jpg on the fly

Patrick Haston
3 February 2009

JPG on the Fly

The Problem

I wanted to include some graphical elements that were beyond anything I could do in HTML.

I knew I could do them using the Java graphics drawing routines, but didn't want to have to include a java applet in my code.

I hit on the bright idea of creating a JPG on the fly which I could just include in my jsp page using a simple img tag.

The Solution

A few searches on Google led me to this jGuru article http://www.jguru.com/faq/view.jsp?EID=159 and that got me most of the way there.

I created a new empty project. I then created this simple Java class:

package uk.co.patrickhaston.jpgdiagram;

import java.awt.Graphics;
import java.awt.image.BufferedImage;

public class JpgDiagram
{
  public JpgDiagram()
  {
  }
  
  public BufferedImage getDiagram(String parameter)
  {
    // Create a new buffered image - you can decide what size to make it
    BufferedImage bi = new BufferedImage(400,300, BufferedImage.TYPE_INT_RGB);

    // get the graphics context 
    Graphics g = bi.getGraphics();

    // Add some graphics - in this case we're just going to write some text
    g.drawString(parameter, 30, 30 );

    // return the buffered image
    return bi;
  }
}

Then I created a very simple jsp page:

<%@page import="javax.imageio.*"%>
<%@page import="java.awt.image.BufferedImage"%>
<%@page import="java.io.*"%>

<jsp:useBean
	id="jpgDiagram"
	scope="request"
	class="uk.co.patrickhaston.jpgdiagram.JpgDiagram"
/>


<%
BufferedImage bufi = jpgDiagram.getDiagram("Hello World");

//Send the converted gif file directly back to 
//browser. You must use setContentType, otherwise you will 
//end up with junk in your browser.
response.setContentType("image/gif"); 
ImageIO.write(bufi,"jpg",response.getOutputStream());
%>

That's all there is to it.