Accessibility
Ryan Favro

Ryan Favro

Blog

Created:
30 July 2007
User Level:
Beginner
Products:
Coldfusion

Image manipulation capabilities in ColdFusion 8

Adobe ColdFusion 8 is shaping up to provide ColdFusion developers an even larger set of features then ever before. This article will explain how you can use the new cfimage tag and image-related functions. The cfimage tag introduces new ways for you to manipulate images in ColdFusion without having to install any third-party image manipulation tags or Java classes.

In this article you will see code snippets from an example gallery that will demonstrate how to resize uploaded images into thumbnails, add a watermark to uploaded images, and use the cfimage tag to create CAPTCHA graphics in the browser.

Requirements

ColdFusion 8

Sample files

Gallery example walkthrough

Figure 1 shows a screen capture of the CFImage Gallery example application included in this article. In this application you can select images from your computer and upload them to the gallery. Before a user can upload an image, they must also successfully enter the matching characters of a CAPTCHA graphic into a corresponding text field. Once an image is uploaded, the application processes the image and performs three actions on the uploaded file. First, it generates a 100 x 100 pixel thumbnail of the image. Second, it scales the large image to fit within 800 pixels of its longest side. Third, it places a watermark in the lower-right corner of the large rescaled image.

The CFImage Gallery example application
Figure 1. The CFImage Gallery example application

Resizing images

When an image is uploaded, the application begins processing it into a thumbnail image of 100 x 100 pixels.

<!--- Upload File ---> 

  <cffile action="upload"
    filefield="file" 
    destination="#ExpandPath('\')#cfimageGallery\images"
    nameconflict="makeunique"/> 

<!--- Assign name of uploaded ServerFile to svrFile variable --->

<cfset svrFile = #File.ServerFile#/>

<!--- Read the Uploaded file to memory and give it a variable name of 
  'mainImage' --->

<cfimage name="mainImage"
  source="#ExpandPath('\')#cfimageGallery\images\#svrFile#" >

<!--- Create thumbnail, note this does not resize the image in memory, 
  just the image that is  written to disk.--->

<cfimage action="resize"
     height="100" 
     width="100" 
     source="#mainImage#"
destination="#ExpandPath("\")#cfimageGallery\images\thumbs\#svrFile#" overwrite="true"/>

In the above code snippet, several things happen to generate the thumbnail. First, the cffile tag uploads the file to the images directory on the server. Second, the uploaded filename is assigned to a variable called svrFile. Third, the cfimage tag reads the uploaded file into an image variable called mainImage. (The default action for cfimage tag is read so you don’t have to specify it explicitly.) Finally, a second cfimage tag reads the image file in memory (source=”#mainImage#”), resizes the image to 100 x 100 pixels, and writes the resized image a new location on the server, overwriting a file with the same name if one exists. Notice that the cfimage tag lets you manipulate images in memory by assigning and using image variables so you don’t have to read and write files to disk each time.

Watermarking an image

Adding watermarks or overlaying one image on top of another in ColdFusion 8 is made possible with the ImagePaste function (see Figure 2). The ImagePaste function takes four arguments. The syntax looks like this:

ImagePaste([bottomImage],[topImage],[x],[y])

The bottomImage and topImage are both ColdFusion images. This means you have to read the images into variables using the cfimage tag's read action first, and then pass them to the ImagePaste function.

figure 02
Figure 2. A watermark added to an image of a Canadian goose

<!--- Overlay a graphic on the original images --> 

<cfimage  name="overlay" 
  source="#ExpandPath('\')#cfimageGallery\overlaygrahpic.gif">

<cfscript> 

// Set Anti-Aliasing on for better image quality when rendered
ImageSetAntialiasing(mainImage,"on"); 

// Scale the image so that the width is no larger then 800 pixels square, and
// use the "bicubic" algorithm to interpolate it for performance.
ImageScaleToFit(mainImage,”800”,”800”"bicubic");

// Calculate the X,Y coordinates to place the overlay graphic in the 
bottom right

// corner, with 20 pixels of padding.

x = ImageGetWidth(mainImage) - ImageGetWidth(overlay) - 20; 
y = ImageGetHeight(mainImage) - ImageGetHeight(overlay) - 20; 

// Paste overlay onto main Image
ImagePaste(mainImage,overlay,x,y);

</cfscript>

<!--- Write the processed file to disk ---> 

<cfimage action="write" 
    source="#mainImage#"
destination="#ExpandPath('\')#\cfimageGallery\images\#svrFile#" 
                 overwrite="true" /> 

This snippet is a direct continuation from the previous example. With the thumbnail resizing completed, the process moves on to pasting a logo graphic onto the uploaded image. The code is also going to resize the uploaded image so that the image's longest dimension (width or height) side is is longer than 800 pixels; the remaining dimension is scaled proportionately. This way, the gallery's full-size images won't be too large for the average screen.

Stepping through this snippet begins by reading the graphic you want to overlay into a cfimage variable called overlay. The source of the overlay image is a GIF file that resides on the server. Moving on, you'll see a cfscript block; this is where most of the magic occurs. To ensure your images don't appear with jagged edges, the code calls another new ColdFusion 8 function called ImageSetAntiAliasing. This function takes two arguments: The first specifies the image to antialias, and the second turns antialiasing on or off. Next, the application scales the image saved in the mainImage variable using the new ImageScaleToFit function. This function takes three arguments: the ColdFusion image to scale, the size in pixels, and the interpolation method. Once the main image is resized for the gallery, the dimensions of the main image and the overlaying image are measured using the ImageGetWidth and ImageGetHeight functions. You will see in the snippet that measurements are used to calculate the of the overlay graphic in the ImagePaste function. Finally, after the image is pasted, the application uses the write action of the cfimage tag to save the modified image to a file.

Create a CAPTCHA image

Another feature included as part of the cfimage tag creates CAPTCHA (Completely Automated Public Turing Test to Tell Computers and Humans Apart) images (see Figure 3).

figure 03
Figure 3. An example of a captcha graphic

The following code snippet shows how to generate the text used for the CAPTCHA image:

<!--- This is our default captcha text--->

<cfset captchaText = "hello"/>

<!--- Form param for the captcha entered text --->

<cfparam name="FORM.captchaTextField" default=""/>

<!--- if the form field "file" is submitted, then process the form submission --->

<cfif isDefined("FORM.file")>

 <!--- Check if the user is human --->

 <cfif captchaText eq TRIM(FORM.captchaTextField)> 
       <cfset isHuman = true />
 <cfelse>
       <cfset isHuman = false/>
 </cfif> 

 <!--- If the user passes as human, then move on to handle the file 
upload ---> <cfif isHuman eq true> <!--- Upload File --->

The following code snippet shows how to use the cfimage tag to generate the CAPTCHA image and display it in the browser.

<!--- Abreviated Form and Table markup--->

<td> 
<cfimage action="captcha" 
         text="#captchaText#"
         difficulty="low" 
         width="140" 
         height="40"/>
</td>

<!--- Continued AbbreviatedConintued Abreviated Form and Table markup--->

In the first code snippet, the text used for the CAPTCHA image is stored in a variable called captchaText. This variable is passed to the cfimage tag's text property in the second code snippet. The remaining code in the first code snippet compares the CAPTCHA text to the text submitted by the user: if they match, ColdFusion allows the file upload to proceed.

In the second code snippet, you will see an abbreviated form containing the cfimage tag with the action property set to captcha, followed by the text property set to the captchaText variable: this is the text that will be displayed in the generated CAPTCHA image. The difficulty property has three settings, low, medium, and high, which affects the degree to which the text is obscured, to make it harder for a computer to distinguish characters. The last two properties, width and height, set the graphic’s display dimensions.

About the author

Ryan Favro is the lead systems architect and managing partner at New Media Team Inc., a Toronto-based web consulting and development company. Ryan has been architecting web application solutions for the past seven years, programming in languages such as ColdFusion, ASP, PHP, and ActionScript. Ryan's other passion, besides testing the limits of the web, is motorcycles. If he's not programming, he is most likely to be out on his motorcycle enjoying Toronto's roadways. Subscribe to Ryan's blog at http://ryanfavro.newmediateam.com/blog/ where you can stay up to date on his Flex and ColdFusion postings.