How do I return an image from a servlet using ImageIO?
Author: Deron Eriksson
Description: This tutorial describes how to use the ImageIO class to return an image from a servlet.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0) || Tomcat 5.5.20
(Continued from page 1) The application's web.xmlW file is shown here. It maps requests to "/image" to the ImageServlet. web.xml<?xml version="1.0" encoding="UTF-8"?> <web-app id="tomcat-demo" 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"> <servlet> <servlet-name>ImageServlet</servlet-name> <servlet-class>test.ImageServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ImageServlet</servlet-name> <url-pattern>/image</url-pattern> </servlet-mapping> </web-app> The "avajavalogo.jpg" file is shown below: avajavalogo.jpgIf I start my application up in TomcatSW (via EclipseSW) and hit the image servletW via http://localhost:8080/tomcat-demo/image in a web browser, we can see that ImageServlet does indeed return the "avajavalogo.jpg" file. ImageIO handles a variety of image formats such as jpegW and pngW. In JavaSW 1.5 (my currently installed version), it reads gifW but does not write gif as far as I know. I read that the gif patent was expiring (or has already expired), so Java 1.6's ImageIO might write gif, but I have not verified this. Related Tutorials: |