Create dynamic images in Java servlets - JavaWorld May
2000
Tutorial Details:
Create dynamic images in Java servlets
Create dynamic images in Java servlets
By: By Ken McCrary
Dynamically convert users' requests into an image
any Websites now use charts and graphs to represent some type of numeric information. In some cases, the chart or graph image is best constructed in realtime. Two reasons could motivate you to build an image dynamically: the data arrives continuously, which lends itself to dynamic image construction; or the data's volume is very large, and dynamic construction dramatically reduces storage. Of course, not every image is a candidate for dynamic construction; it's just another tool available in the Web developer's toolbox.
Image I/O packages, JDK-level requirements
If your servlet is to generate images on the fly, you first need to do image I/O (input/output). Specifically, you need to generate an image in response to an HTTP request. The core Java API provides no direct facility for saving images of any type. However, you can use Sun's Java 1.1 class library to do image I/O. Also, Sun's 1.2 image I/O offering includes a proprietary package for encoding and decoding JPEG images. Since this code is in a com.sun package, it is not part of the core API and is not a standard extension; therefore, its dependent code is not portable. The good news is that the approved Java Specification Request, JSR-000015, for a standard Java 2 extension, provides a framework for performing image I/O. This adds support to the Java 2 platform for image I/O and provides a mechanism to write portable code capable of dynamic image I/O. For this article, I create two examples, one using the Java 1.1 image I/O framework and the other using Java 1.2 code.
Image formats
The most common image format on the Web is GIF. GIF is widely supported by browsers, even old ones. Unfortunately, for writing image-generation code, GIF is potentially encumbered legally by a patent on its compression scheme. The two examples in this article create a JPEG and a PNG image. I will generate a JPEG image primarily because Sun's Java 1.2 code lets me generate this type of image. One difference between the GIF format and the JPEG format is that the GIF-compression algorithm is lossless, meaning that when the image data is subjected to a compress/decompress cycle the resulting data is identical to the original data (no information is lost); the JPEG algorithm is not lossless. Usually, the image degradation is not visible for the type of image you are generating. The second example generates a PNG image, which uses a lossless compression algorithm free of legal issues.
Image servlet design
For this article, I will decompose the image presentation system into two parts. The first part, the Image servlet, is responsible for responding to image requests and returning either an image or an error to the client. The second part is a class capable of performing image I/O. For simplicity, the type of image generated is determined by passing the name of a Java class, which should generate the image to the Image servlet. The Java class implements a simple interface for communication with the servlet. The following code shows the interface that the ImageProducer class must implement:
public interface ImageProducer
{
/**
* Request the producer create an image
*
* @param stream stream to write image into
* @return image type
*/
public String createImage(OutputStream stream) throws IOException;
}
The ImageProducer interface consists of a single method, with a parameter to provide a stream for which the image is output and a returned string indicating the type of image -- for example, image/jpg .
The following code indicates how the servlet works with the ImageProducer to produce the image:
ImageProducer imageProducer =
(ImageProducer)
Class.forName(request.getQueryString()).newInstance();
String type = imageProducer.createImage(response.getOutputStream());
response.setContentType(type);
This code attempts to load a class named by the query string in the URL. The query string is the portion of the URL after the ? . The loaded class is then cast to an ImageProducer and asked to create an image. If everything goes well, the resulting image is returned to the client.
There are several exception types that can arise from this code; the most common are ClassNotFoundException and ClassCastException . The former results from the named ImageProducer not being available to the Classloader that loaded the servlet, and the latter results from the named class not implementing the ImageProducer interface. In the event an exception occurs, the client of course does not receive an image, and the browser displays a graphic indicating that no image was returned by the Web server. The code was tested using the Java Server Web Development Kit (JSWDK) 1.0.1, but you should get similar results on most Web servers supporting Java servlets.
Image generation on Java 1.1
For my first generated image, I will create code I can deploy on the Java 1.1 platform. Although 1.2 JVMs are fairly common, not everyone can count on deploying code on the latest platform. Some commercial Web-hosting environments, for example, are somewhat slow to update the Java Runtime Environments (JREs) on their servers. This means that any servlets you deploy must run on Java 1.1. Designing the code for Java 1.1 does not greatly complicate matters; however, I do discuss a troublesome issue regarding in-memory image creation later in the article.
I will create the image of a simple pie chart. A pie chart is a useful, easy-to-read chart. This pie chart will be complete with colorization and labeling of the pie's pieces. The chart will indicate soft drinks favored by software developers. Now I'll take a look at how you can go about this.
For doing image I/O on Java 1.1, Sun offers a class library known as Jimi. Sun purchased this class library from a small software vendor. After Sun began distributing the class library, it repackaged the classes into com.sun , but otherwise left them unchanged. The following are the steps you should take to produce a PNG image using the Jimi toolkit.
Construct a Frame window to provide an AWT image.
Use the AWT image to get a Graphics instance.
Draw into the Graphics object.
Create a JimiWriter using the HTTP output stream.
Have the JimiWriter write out the AWT image previously created.
On the Java 1.1 platform, constructing an in-memory image appears to require that an AWT component exist on the desktop. Normally, you should not use Java servlet code to create AWT components. It just doesn't make sense for the Web server to create user interface components to respond to a client request. In this case however, you need an image to provide a Graphics instance that you can draw into. So, you will have to live with the small window that appears on the Web server's desktop. If you know of a way to create an image on Java 1.1 without an AWT component, please let me know. One possible design would use a template image on the Web server's disk. You could load the image data from the disk, and construct the AWT image using java.awt.Toolkit.createImage() . After you construct the AWT image, it can provide the Graphics instance, which you can draw into as usual. If this works, you could avoid the spurious window. I will leave this experiment as an exercise to the interested reader.
First of all, the connection between the servlet and the class to produce the pie chart is the interface discussed earlier, ImageProducer . When you construct JIMIProducer , the ImageProducer for the pie chart, it will create an AWT frame, an AWT image, and subsequently an AWT graphics context. The following code sample is from the JIMIProducer :
Frame f = new Frame();
f.setVisible(true);
image = f.createImage(ImageWidth, ImageHeight);
graphics = image.getGraphics();
f.setVisible(false);
The key method in the JIMIProducer class is drawSlice() . Given a label and the number of degrees the slice should consume, the class draws a slice of the pie chart and colorizes it. Next, I'll discuss the way this method works and revisit some high school geometry while I'm at it.
You begin drawing the pie chart internals at the three o'clock position; that is, you draw a line from the chart's center to the three o'clock point on the bounding oval. After you draw the initial line, you draw each additional line in a clockwise direction. The following code takes the number of degrees passed to the method and draws a line reflecting a pie slice with that angle. The calculation first converts the angle to radians; I start with degrees because it seems more natural. At any rate, the angle is converted to Cartesian coordinates. This x and y value is then used as an offset to the chart's center point. A line is subsequently drawn from the center to the calculated point. This process is repeated for each call to the drawSlice method; the accumulated calls to this method should total 360 degrees, or the pie chart will not look right.
//***************************************************************
// Convert to radians
// 1 degree = pi/180 radians
//***************************************************************
double theta = degrees * (3.14/180);
currentTheta += theta;
//***************************************************************
// Convert to x/y
// x = r cos @
// y = r sin @
//***************************************************************
double x = Radius * Math.cos(currentTheta);
double y = Radius * Math.sin(currentTheta);
Point mark2 = new Point(center);
mark2.translate((int)x,(int)y);
graphics.drawLine(center.x, center.y, mark2.x, mark2.y);
The next step is to provide a unique color for the new pie slice. The following code illustrates how you can do this. The handy fillArc() method makes it easy to color the pie slice.
graphics.setColor(colors[colorIndex++]);
graphics.fillArc(Inset,
Inset,
PieWidth,
PieHeight,
-1 * lastAngle,
-1 *
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: Create dynamic images in Java servlets - JavaWorld May
2000
View Tutorial: Create dynamic images in Java servlets - JavaWorld May
2000
Related
Tutorials:
Create a scrollable virtual desktop
in Swing
Create a scrollable virtual desktop
in Swing |
Bridge the gap between Java and Twain
Bridge the gap between Java and Twain |
Enhance your J2EE presentation layer
Enhance your J2EE presentation layer |
Filtering and Transforming Digital Images
Filtering and Transforming Digital Images
In this Issue
Welcome to the Core Java Technologies Tech Tips for April 7, 2004. Here you\'ll get tips on using core Java technologies and APIs, such as those in Java 2 Platform, Standard Edition (J2SE).
|
RMI, Dynamic Proxies, and the Evolution of Deployment
RMI, Dynamic Proxies, and the Evolution of Deployment
Dynamic Generation of Stub Classes
This release adds support for the dynamic generation of stub classes at runtime, obviating the need to use the Java Remote Method Invocation (Java RMI) stub compi |
Jython
Get to know Jython, in this first article in a new series introducing alternate languages for the Java Runtime Environment, alt.lang.jre. Jython is an implementation of the popular scripting language Python, but running on a JVM. For Python developers Jyt |
First Step towards JDBC
This article introduce you with JDBC and shows you how to create a database application to access the databases. |
Internet & Intranets: Java Servlets
What are servlets?
"Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to upd |
Java Servlets: Design Issues
This article covers the principal concepts associated with servlets. This article examines some of the design issues, and offers some guidelines on the applicability of Java servlets for web based application development. |
JSP (JavaServer Pages) is a standard for combining Java and HTML to provide dynamic content in web pages.
With JSP, you embed Java code in HTML using special JSP tags similar to HTML tags. You install the JSP page, which has a .jsp extension, into the WebLogic Server document root, just as you would a static HTML page. When WebLogic Server serves a JSP page.. |
Professional Java Server Programming.
An overview of the new server-side Java platform - Java 2 Enterprise Edition - as it relates to building n-tier web applications. |
alaJSP JSP-similar processor
It is yet another servlet based preprocessor. The common idea behind that line of the products (see ColdCafe site) is splitting static HTML presentation which done by designers and dynamic proceed developed by programmers. |
Introduction to Servlets, JSP, and Servlet Engines
Servlets are the Java Technologies' answer to CGI programming. They are programs which run on the server side and generate dynamic content. Why would one prefer to use Servlets over traditional CGI programming? |
This tutorial shows how to Combine the power of XPath and JSP tag libraries
In this article, we'll examine the XPath custom tag library for JSPs and see a tag collection that provides simple control constructs and a uniform attribute value substitution facility, all of which combine to reduce complexity and improve functionality. |
Introduction To Enterprise Java Bean(EJB). Developing web component.
Introduction To Enterprise Java Bean(EJB). Developing web component.
Developing web component
Introduction To Java Beans
J2EE specification defines the structure of a J2EE application. According to the specification J2EE application consists of |
Introduction to the JSP Java Server Pages
Introduction to the JSP Java Server Pages
Welcome to JSP Section
Introduction To JSP
Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server side scripting support for creating database |
Accessing Database from servlets through JDBC!
Accessing Database from servlets through JDBC!
Java Servlets
J ava Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was developed to provide server side capabilities |
Techniques used for Generating Dynamic Content Using Java Servlets.
Techniques used for Generating Dynamic Content Using Java Servlets.
Techniques used for Generating Dynamic Content
Common Gateway Interface (CGI)
For any web application high performance and timely delivery are key ingredients to competitive |
Building Search Engine Applications Using Servlets !
Building Search Engine Applications Using Servlets !
Building Search Engine Applications Using Servlets
Please visit http://www.webappcabaret.com/javadevelopers/search to see running copy of our search engine.
Introduction
This tutorial takes |
VolatileBufferedToolkitImage Strategies
Ever wondered what kind of image to use in your application? Or what method to use in creating it? This article attempts to address this challenging topic. |
|
|
|