Friday, November 9, 2007

Dynamic images in Web Dynpro for Java

It’s a common problem displaying dynamic images in Web Dynpro 4 Java. The image widget takes only an URL as source argument, and not an byte array as you might expect.

There is two solutions to that problem, one is to store the images on the web serves file system an generate an URL based on the filename and location. This solution involves setting up a HTTP Alias in the WAS and manually maintaining the image cache in the file system of the WAS. How to set up the alias and make it work is documented in detail in the blog of Renjith Andrews called Creating an HTTP Alias in WAS. As the seems to be the common approach, I cannot recommend it since the overhead of maintaining the image cache will be to much to handle.

In stead I will suggest another approach where you do not need the local file system nor do you need to maintain the image cache. My recommendation is utilizing the IWDResourse.

The following little piece of code will show you how to translate a byte array of an gif image to an URL:

// get the image data from somewhere
byte[] data = new byte[1024];

// Create a cached web resource using the WDResourceFactory
IWDResource res = WDResourceFactory.createCachedResource
(data, "image.gif", WDWebResourceType.GIF_IMAGE);

String url = res.getUrl(0); // 0 means "AUTO"

For a JPEG image the process is the same but use WDWebResourceType.JPG_IMAGE as the last argument of the the call to the factory.

It is as simple as that. Since it is a cached web resource, you can add it to your context for storage while the application is running so you won’t have to waste CPU cycles to create the same IWDResource over and over again. Ad by adding it to the context it will get automatically cleaned up when the application session ends.

1 comment:

Anonymous said...

Thanks a lot! That's helped a great!