Streaming an image directly in Cold Fusion using csImageFile

This page describes a technique for streaming an image to the browser in Cold Fusion while avoiding the need to save the file temporarily first. It makes use of the PageContext Java Object, which is part of the J2EE integration.

As explained elsewhere, the script that streams the image is called by putting it inside an <img> tag in a web page. This script then calls the csImageFile component to generate an image in some way and it sends it to the browser. It must not contain any other output besides the image. The first line of the code must be:

<cfcache action="flush">

The following code will stream a JPG image, assuming that the csImageFile object has been created, using the variable name "Image" and it contains an image:

<cfscript>
Context = GetPageContext();
Context.SetFlushOutput(false);
Response = Context.GetResponse().GetResponse();
Out = Response.GetOutputStream();
Response.SetContentType("image/jpeg");
Out.Write(Image.JPGData);
Out.Flush();
Response.Reset();
Out.Close();
</cfscript>

For other image types, set the Content Type to the appropriate value, e.g. "image/gif" for GIF and "image/png" for PNG.

Other Components and File Types

The same technique can be used with some of our other components. csASPGif and csDrawGraph also produce dynamic images while csASPZipFile can produce zip files dynamically for streaming to the browser.