jGuru
Register Email     Password Forgot your
password?
HOME FAQS FORUMS DOWNLOADS ARTICLES PEERSCOPE LEARN

  Search   jGuru Search Help

Question How do I create an image (GIF, JPEG, etc.) on the fly from a servlet?
Topics Java:API:AWT:Graphics, Java:API:Servlets:Images
Author Alex Chaffee PREMIUM
Created Sep 3, 1999 Modified Dec 16, 2001


Answer

To create an image or do image processing from Java, there are several packages and classes available. See the Purple Servlet References for a list.

Once you have an image file in your servlet, you have two choices:

  1. Write the file to disk and provide a link to it. Make sure you write it to a location that's in your web server directory tree (not just anywhere on the server's disk). You can use the Java 2 JPEGCodec class, or Acme Labs' GIFEncoder class, to turn a Java Graphics into an image file or bytestream.

    (Note that in some servlet engine setups, the servlet directory is not accessible by the web server, only by the servlet engine, which means you won't be able to access it through an http:// URL.) You can either send an IMG tag in the HTML your servlet is outputting, or send an HTTP redirect to make the browser download the image directly (as its own page).

    (CookieDetector (http://www.purpletech.com/code/CookieDetector.html) has an example, with source code, of sending a redirect.)

    Pro: the image can be cached by the browser, and successive requests don't need to execute the servlet again, reducing server load.

    Con: the image files will never be deleted from your disk, so you'll either have to write a script to periodically clean out the images directory, or go in and delete them by hand. (Or buy a bigger hard disk :-) ).

  2. Output the image directly from the servlet. You do this by setting the Content-type header to image/gif (for GIFs), or image/jpeg (for JPEGs). You then open the HttpResponse output stream as a raw stream, not as a PrintStream, and send the bytes directly down this stream using the write() method.

Focus on Java (http://java.miningco.com/library/weekly/aa090299.htm) has a brief article describing the use of the Java 2 JPEGCodec class.

You can also use JIMI to read and write images in many formats, including GIF, JPEG, TIFF (TIF), PNG, PICT, Photoshop, BMP, Targa, ICO, CUR, Sunraster, XBM, XPM, and PCX.

See also:



Is this item helpful?  yes  no     Previous votes   Yes: 4  No: 1



Comments and alternative answers

Comment on this FAQ entry

Remember the IMG tag
Alex Chaffee PREMIUM, Dec 16, 2001  [replies:1]
Remember, to display an image inside an HTML page, you have to use the IMG tag, like
<IMG src="/mywebapp/myimageservlet">
Just writing the data to the servlet response isn't going to work, unless you're writing an entire image/gif or image/jpeg document.

Is this item helpful?  yes  no     Previous votes   Yes: 2  No: 1



Reply to this answer/comment  Help  
code to write imgs on the fly from a jsp
kamalesh kam, Mar 28, 2004
<%@ page import="javax.servlet.http.*"%> <%@ page import="java.io.*"%> <%@ page import="java.awt.*"%> <%@ page import="java.util.Random"%> <%@ page import="java.awt.Color"%> <%@ page import="java.awt.image.*"%> <%@ page import="Acme.JPM.Encoders.GifEncoder"%> <%@ page import="com.sun.image.codec.jpeg.JPEGCodec"%> <%@ page import="com.sun.image.codec.jpeg.JPEGImageEncoder"%> <%BufferedImage image= new BufferedImage(500,500, BufferedImage.TYPE_INT_RGB); Graphics g=image.getGraphics(); Random r=new Random(); g.fillRect(r,r,r,r); FileOutputStream fos=new FileOutputStream("c:/ewr.jpg"); JPEGImageEncoder encoder= JPEGCodec.createJPEGEncoder(fos); encoder.encode(image); %>

Is this item helpful?  yes  no     Previous votes   Yes: 1  No: 0



Reply to this answer/comment  Help  
Jake stone adds source code
Alex Chaffee PREMIUM, Dec 16, 2001  [replies:5]
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {

        File f = new File(System.getProperty("user.home")+"\\zoewrap.jpg");
        JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new FileInputStream(f));
        BufferedImage image =decoder.decodeAsBufferedImage() ;

        // Send back image
        ServletOutputStream sos = response.getOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
        encoder.encode(image);
    }





Is this item helpful?  yes  no     Previous votes   Yes: 3  No: 0



Reply to this answer/comment  Help  
Re: Jake stone adds source code
Ping Long PREMIUM, May 15, 2002  [replies:2]
Alex,
I got cached image problem in my application. I need to update image without changing name.
Your idea may fix my problem. I would like to know when I can get those classes such as:
JPEGImageDecode, JPEGImageEncoder, JPEGCodec.
Thanks in advance.
PL

Is this item helpful?  yes  no     Previous votes   Yes: 1  No: 0



Reply to this answer/comment  Help  
Re[2]: Jake stone adds source code
jpeg jones, May 20, 2002  [replies:1]

These classes are in the com.sun.image.codec.jpeg. package; they should be in your jdk 1.3 (or whatever) src.jar

Is this item helpful?  yes  no     Previous votes   Yes: 1  No: 0



Reply to this answer/comment  Help  

Re[3]: Jake stone adds source code
Ohad Kravchick, Nov 14, 2002
I have a problem with that. i made a painter applet, and i need to write the result of the painting to the server (asp). i've created an asp page which gets posted data, from the applet (ACME.GifEncoder), and it still doesnt work. will you please help me, i'm stuck badly. go and take a look at the painter: my Painter send me email for response.....

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Regarding the cache problem
Thomas Isaksen, Dec 9, 2003
I think I had the same problem when trying to display an image fetched from a servlet talking to the db. I simply added another parameter to the url which caused the cache problem to go away:
First I had: <img src="/servlet/ImageServlet?id=n"/>
which didn't work, it was cached and showed the same image all the time.
So I put this in:
<img src="/servlet/ImageServlet?id=n&rnd=some_random_number"/>
and the image caching problem is gone :-)
"some_random_number" can be as simple as putting the value of System.currentTimeMillis() or using java.util.Random to come up with a value.
Hope this helps.

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: Jake stone adds source code
dalal salih, Feb 23, 2010
package

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Convert image from one format to another on the fly. JAI versus ImageIO.
Master Wong, Feb 24, 2006  [replies:4]

You can use either Java Advance Imaging JAI (com.sun.media.jai) or Java ImageIO (javax.imageio).

In case you are as confuse as I was about JAI and ImageIO, the short answer is: you should not use JAI anymore. It's old. JDK 1.4 shipped with javax.imageio to replace JAI. So, as long as you have JDK 1.4 or greater installed, no additional package is needed.

So, here's code to convert TIFF to whatever format in a JSP. In my example, to a GIF file.

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

<%
File myTifFile = new File("aTifFile.tif");

//Option1: write the converted gif file to disk
File myGifFile = new File("aGifFile.gif");
BufferedImage bufi = ImageIO.read(myTifFile);
ImageIO.write(bufi,"gif",myGifFile);

//Option2: 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,"gif",response.getOutputStream());
%>


That's it! Isn't that easy!!! Another thing is, the documentation on Sun says ImageIO doesn't support writing to GIF format. But that's not the case, well, at least not in my case. I was able to convert a TIFF  file to a GIF file with no problem. The list of supported write formats may be obtained by:

<%
String[] writerFormatNames = ImageIO.getWriterFormatNames();

for (int i=0;i<writerFormatNames.length;i++) {
    System.out.println(writerFormatNames[i]);
}
%>

Here are some great  references:

Hope this help.

Cheers,
Royce



Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: Convert image from one format to another on the fly. JAI versus ImageIO.
Master Wong, Mar 15, 2006

CORRECTION:

The default javax.imageio comes with JDK 1.4.2 only supports limited image formats (both readers and writers).

In my previous post, I said "I was able to convert a TIFF file to a GIF file with no problem." because I didn't realize that I already have "Java Advanced Imaging Image I/O Tools" installed.

You can get Java Advanced Imaging Image I/O Tools at:
http://java.sun.com/products/java-media/jai/downloads/download-iio-1_0_01.html

If you don't have the tools package install, you will keep getting NULL from ImageIO.read(...) if you try to read in say a TIFF file.



Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: Convert image from one format to another on the fly. JAI versus ImageIO.
KIRAN REDDY, Apr 12, 2006  [replies:2]
i could not convert the tiff image to jpeg can anyone help me with the example code.if possible please send me the code.
i am using this application in jsp.
server tomcat4
java tool kit-jdk1.4


Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[2]: Convert image from one format to another on the fly. JAI versus ImageIO.
Master Wong, May 4, 2006  [replies:1]

On top of the your regular JDK, you will need the additional "Java Advanced Imaging Image I/O Tools" to read in your TIFF file. You can get it at:
http://java.sun.com/products/java-media/jai/downloads/download-iio-1_0_01.html


---The following is the JSP code---
<%@page import="javax.imageio.*"%>
<%@page import="java.awt.image.BufferedImage"%> 

<%
File myTifFile = new File("aTifFile.tif");

//Option1: write the converted gif file to disk
File myGifFile = new File("aGifFile.gif");
BufferedImage bufi = ImageIO.read(myTifFile);
ImageIO.write(bufi,"JPEG",myGifFile);

//Option2: 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/JPEG"); 
ImageIO.write(bufi,"JPEG",response.getOutputStream());
%>

Good luck



Is this item helpful?  yes  no     Previous votes   Yes: 1  No: 0



Reply to this answer/comment  Help  
Re[3]: Convert image from one format to another on the fly. JAI versus ImageIO.
Jaleel Ahmed, May 26, 2006

but that will send only the image to the browser since you have set the response type to image/jpeg . how to embed the image along with other html tags.

for example i want to display the image along with an html form below the image



regards ab

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  


Ask A Question



 
Related Links

AWT FAQ

AWT Forum

Sun's AWT Home Page

The Java Tutorial (Good AWT & Swing Coverage)

Effective Layout Management

Layout Manager Launch

Creating a Custom Layout Manager

Drag and Drop resources

Servlets FAQ

Servlets Forum

Servlet-related resource list from Purple Technology

jGuru JSP FAQ

Sun Servlet Home Page

java.isavvix.com

Wish List
Features
About jGuru
Contact Us

 


Internet.com
The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers