DYNAMIC IMAGE CREATION
IN SERVLETS
using sun.image.codec.JPEG & NIO.
by
rs.ramaswamy@gmail.com
---------------------------------------------
In this brief tutorial, the
author gives demos for image
creation in servlets, using the conventional
methods as well as the new methods introduced in JDK1.4 (nio).
--------------------------------------
There are three technolgies now in the web
tier competing with each other, namely, ASP.net, Servlets/JSP and PHP.
There are some special tasks that are
common to all these three. One such is the creation of Dynamic image from the
server side. Whatever be the technology, the general method is to create a
canvas in the server side, draw the required graphics on that canvas and then
send the encoded canvas to the browser. The encoding may be either GIF or JPEG
or PNG.
-----------------------------------
If
the encoder is GIF type, there was a problem in servlets. The required encoder
is not available in JDK and we
have to download the software from acme
website. But, if it is JPEG, the required encoder has been available in JDK
itself since, JDK1.2, though it has not been quite well known! In this
tutorial, we will see both the methods.
The JPG method is easier as we do not need
any extra software. ( Another problem with the Gif encoder is that it is not
free for commercial use).Jason Hunter , the author of the classic book
on Servlets, has devoted quite a few pages for this topic but has used the GIF
encoder only. Many other books dealing with this topic also, use GIF encoder. It
is only in the web-articles, that we come across the JPG encoder, built into
JDK!
-----
Our aim is to superimpose the string entered by the user through the
html form on an image created in the server side . In our example, we are using
'birds.gif' in the server.
===========================================
// confidential.htm
<html>
<body>
DEMO FOR DYNAMIC SUPER-IMPOSING
OF MESSAGRE
ON PICTURE
<form method=post
action='http://localhost:8080/servlet/
confidential'>
<input type=text
name='text1'><br>
<input type=submit>
</form>
</body>
</html>
--------------------------------------
There is nothing special in the html file. The
servlet code accepts the string from the user.
Then it
creates a frame in the server side. Hence, we have imported java.awt.*;
The frame is required to draw the image.
'frame1.addNotify()' connects the
frame to the host platform’s AWT toolkit.
A graphics canvas is then created and the
image is drawn over that canvas. MediaTeacker is needed to check if all the
bits of the image have been loaded before proceeding further. The response's
content-type is set as image/gif. Then
the canvas is encoded and sent to the browser.
The problem will be in compiling the source
file. We have placed acme.jar in c:\ drive and we are using tomcat3.2 for simplicity. We give classpath to
c:\tonmcat3.2\lib\servlet.jar;
c:\acme-gifencoder.jar .
Now we can easily compile. The class file
is as usual placed in
c:\tomcat4.2\webapps\root\web-inf\classes folder. The corresponding html file
is placed in
c:\tomcat3.2\webapps\root.
Now, we start tomcat3.2 and type the URL in
browser as 'http://localhost:8080/confidential.htm'
We type 'DAS' in the textbox and we get
this super-imposed over the picture of 'birds' as shown in confidential.gif.The
source code has been given in confidential.java
--------------------------------------------
// confidential.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.awt.*;
import Acme.JPM.Encoders.GifEncoder;
public class confidential extends
HttpServlet
{
public void doPost
(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException
{
String
s = request.getParameter("text1");
ServletOutputStream out=response.getOutputStream();
try
{
Frame frame1=new Frame();
frame1.addNotify();
Image canvas
=frame1.createImage(400,400);
Graphics g=canvas.getGraphics();
//----------------
MediaTracker mt = new
MediaTracker(frame1);
Image image1=
Toolkit.getDefaultToolkit().getImage
("c:\\birds.gif");
mt.addImage(image1, 0);
try {
mt.waitForAll(); }
catch (Exception e1) {out.println(""+e1);}
g.drawImage(image1,50,50,frame1);
Font
font1 =
new Font("Times Roman",Font.BOLD,32);
g.setFont(font1);
g.setColor(Color.red);
g.drawString("CONFIDENTIAL",50,50);
g.drawString (s,50,150);
//-----------------------
response.setContentType("image/gif");
GifEncoder encoder=
new GifEncoder(canvas,out);
encoder.encode();
}
catch(Exception e1)
{System.out.println(""+e1);}
}
}
==============================================
We will now repeat the same demo, without
using any external gifencoder but using the JPGEncoder available in JDK
itself.
Our files for this demo will be :
confidentialjpg.htm &
confidentialjpg.java
-------------------------------------------
// confidentialjpg.htm
<html>
<body>
DEMO FOR DYNAMIC SUPER-IMPOSING
OF MESSAGRE ON PICTURE
<form method=post
action='http://localhost:8080/servlet/confidentialjpg'>
<input type=text
name='text1'><br>
<input type=submit>
</form>
</body>
</html>
==============================================
It may be noted that the JPGDecoder
is used to create a buffered image from the jpg file. This is very elegant and
does away with the need for creating a frame and then getting a canvas in that
frame.Otherwise, the code follows the same pattern. as before.
As we are not using any external package,
it is enough if we give classpath as:
c:\tomcat3.2\lib\servlet.jar
We can compile without any problem. The
resulting display in browser has been shown as 'clintondas.gif'.
============================================
// confidentialjpg.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;
public class confidentialjpg
extends
HttpServlet
{
public void doPost
(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException
{
String
s = request.getParameter("text1");
ServletOutputStream out=
response.getOutputStream();
try
{
FileInputStream fis = new FileInputStream("c:\\clinton.jpg");
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(fis);
BufferedImage image1=
decoder.decodeAsBufferedImage() ;
//----
BufferedImage image=
new BufferedImage(500,500, BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
Font
font1 = new Font("Times Roman",Font.BOLD,64);
g.setFont(font1);
g.setColor(Color.red);
g.drawString(s,100,100);
g.drawImage(image1,100,100,null);
ServletOutputStream sos = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
encoder.encode(image);
}
catch(Exception e1)
{System.out.println(""+e1);}
}
}
============================================
JDK 1.4 introduced the NEW-IO (Input-output
package).It includes ImageIO.It gives a
straight method to read and write picture files such as GIF, PNG and
JPEG. We will see how we can modify our
previous servlet to read three image files, such as 'birds.gif', 'clinton.jpg'
and 'jedit.png'
and then send these three imaages drawn on
a canvas to the browser.
-------------------------------------
// confidentialnio.htm
<html>
<body>
DEMO FOR DYNAMIC SUPER-IMPOSING
OF MESSAGRE ON PICTURE
<form method=post
action='http://localhost:8080/servlet/
confidentialnio'>
<input type=text
name='text1'><br>
<input type=submit>
</form>
</body>
</html>
============================================//
confidentialnio.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import com.sun.image.codec.jpeg.*;
public class confidentialnio extends
HttpServlet
{
public void doPost
(HttpServletRequest
request,
HttpServletResponse response)
throws ServletException,IOException
{
String
s = request.getParameter("text1");
ServletOutputStream out=
response.getOutputStream();
try
{
File
file1 =
new File("c:\\birds.gif");
BufferedImage image1 =ImageIO.read(file1);
File
file2 =
new File("c:\\clinton.jpg");
BufferedImage image2 =ImageIO.read(file2);
File file3 =
new File("c:\\jedit.png");
BufferedImage image3 =ImageIO.read(file3);
//----
BufferedImage canvas=
new BufferedImage(300,500, BufferedImage.TYPE_INT_RGB);
Graphics g=canvas.getGraphics();
Font font1 = new Font
("Times Roman",Font.BOLD,64);
g.setFont(font1);
g.setColor(Color.red);
g.drawString(s,100,100);
g.drawImage(image1,50,50,null);
g.drawImage(image2,50,200,null);
g.drawImage(image3,50,350,null);
ServletOutputStream sos = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
encoder.encode(canvas);
}
catch(Exception e1){System.out.println(""+e1);}
}
}
=============================================
As
this is available only in JDK1.4, we must set path to:
d:\jdk1.4.2\bin
and then compile the servlet.
Similarly, for tomcat3.2, we must set
JAVA_HOME to d:\jdk1.4.2 and then start
it.
We are able to compile and exceute without
any problem and we get all the three types of images displayed in the same
canvas. as shown in 'nio.gif'.
==========================================