Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
7.5 Using Servlets to Generate GIF Images
169
2. Draw into the 
Image
.
You accomplish this task by calling the 
Image
's 
getGraphics
method and then using the resultant 
Graphics
 object in the 
usual manner. For example, with JDK 1.1, you would use vari 
ous 
drawXxx
 and 
fillXxx
 methods of 
Graphics
 to draw 
images, strings, and shapes onto the 
Image
. With the Java 2 
platform, you would cast the 
Graphics
 object to 
Graphics2D
, 
then make use of Java2D's much richer set of drawing opera 
tions, coordinate transformations, font settings, and fill patterns 
to perform the drawing. Here is a simple example:
Graphics g = img.getGraphics();
g.fillRect(...);
g.drawString(...);
3. Set the 
Content Type
 response header.
As already discussed, you use the 
setContentType
 method of 
HttpServletResponse
 for this task. The MIME type for GIF 
images is 
image/gif
. 
response.setContentType("image/gif");
4. Get an output stream.
As discussed previously, if you are sending binary data, you 
should call the 
getOutputStream
 method of 
HttpServlet 
Response
 rather than the 
getWriter
 method.
OutputStream out = response.getOutputStream();
5. Send the 
Image
 in GIF format to the output stream.
Accomplishing this task yourself requires quite a bit of work. 
Fortunately, there are several existing classes that perform this 
operation. One of the most popular ones is Jef Poskanzer's 
GifEncoder
 class, available free from 
http://www.acme.com/java/
. Here is how you would use this 
class to send an 
Image
 in GIF format:
try {
new GifEncoder(img, out).encode();
} catch(IOException ioe) {
// Error message
}
Listings 7.8 and 7.9 show a servlet that reads 
message
, 
fontName
, and
fontSize
 parameters and uses them to create a GIF image showing the mes 
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

jsp web hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Jsp Web Hosting Cheapest Web Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved