File Watcher Event gateway CFC for Jpeg thumbnail resizing

By David Fekke
January 17th, 2011

I gave a presentation last year on the Event Gateway for ColdFusion MX 7. John Lyons asked me to post the code for the CFC I used in my presentation to my blog.

The way this code works is that it uses a File watcher event gateway to see if any files of type jpg are written to a folder specified in the Event Gateway. Here is the code for the CFC.


<cffunction name="onAdd" access="public" returntype="void">
<cfargument name="CFEvent" type="struct" required="true">

<cflog file="MydirWatcher" application="No" text="ACTION: #data.type#; FILE: #data.filename#; TIME: #timeFormat(data.lastmodified)#">

<cfset createThumbImage(data.filename) />
<cfcatch type="any">
<cfwddx action="cfml2wddx" input="#cfcatch#" output="myWDDX" />
<cflog file="MydirWatcher" application="No" text="#myWDDX#">

<cffunction name="createThumbImage" access="public" returntype="void">
<cfargument name="filepath" type="string" required="yes" />
<cfset var imageName = "Thumb" & getFileFromPath(arguments.filepath) />
<cfset var ImageIOObj = CreateObject("Java", "javax.imageio.ImageIO") />
<cfset var FileInputStream = CreateObject("Java", "") />
<cfset var FileOutputStream = CreateObject("Java", "") />
<cfset var newImage = createObject("java", "java.awt.image.BufferedImage") />
<cfset var AffineTransform = CreateObject("Java", "java.awt.geom.AffineTransform") />
<cfset var AffineTransformOp = CreateObject("Java", "java.awt.image.AffineTransformOp") />

<!--- Ideal ratio is 128 pixels by 128 pixels --->
<cfset FileInputStream.init(arguments.filepath) />

<!--- Set the new dimensions for the thumbnail based on the image ratio. --->
<cfif imageRatio GT 1>

<cfset newWidth = 128 * (width/height) />

<cfset newHeight = 128 * (height/width) />

<cfset pWidth = newWidth / Width />
<cfset pHeight = newHeight / Height />

<cfset jwidth = javaCast("int", newWidth) />
<cfset jheight = javaCast("int", newHeight) />

<cfset newImage.init(jwidth, jheight, imageType) />
<cfset AffineTransform.scale(pWidth, pHeight) />
<cfset AffineTransformOp.init(AffineTransform, AffineTransformOp.TYPE_BILINEAR) />
<cfset AffineTransformOp.filter(Image, newImage) />

<cfset FileOutputStream.init("c:\thumbnails#imageName#") />
<cfset ImageIOObj.write(newImage, "jpg", FileOutputStream) />

<cfset Image.flush() />
<cfset FileOutputStream.close() />

This code uses the underlying Java libraries that are included with ColdFusion to resize the images.

Doug Hughes has written an Image component that takes advantage of these underlying java libraries. I highly recommend that if you need to do image processing in your web app, that you take a look at some of the components that Doug sells at his company Alagad. He also sells a component for doing Capchas.

← Previous Page  Next Page →