Resizing an image with CFImage (Creating a Thumbnail)
Coldfusion, cfimageYesterday, I got an email asking for some help on using CFImage to create thumbnails on a image that was submitted / uploaded through a form. Here's a quick and dirty example of how to do just that.
<cfif Isdefined('form.FileUpload') and form.FileUpload NEQ ''>
<!--- upload the image file from the form submission --->
<cffile action="upload"
fileField="FileUpload"
destination="#ExpandPath('/dev/images/')#"
nameconflict="makeunique">
<!--- Read the image, this only needs to be done once --->
<cfimage name="TempImage"
source="#cffile.ServerDirectory#/#cffile.ServerFile#"
action="read">
<!--- store image properties in a struct --->
<cfimage action="info" structName="anImageStruct" source="#TempImage#">
<!--- write the image out to the browser --->
<p>Original Image (<cfoutput>#anImageStruct.width# X #anImageStruct.height#</cfoutput>)<br/>
<cfimage action="WriteToBrowser" source="#TempImage#"></p>
<!--- set the resize params --->
<cfset ImageSetAntialiasing(TempImage,"on") />
<cfset targetWidth = 100>
<cfset ratioDivider = anImageStruct.width / targetWidth>
<cfset width = anImageStruct.width / ratioDivider>
<cfset height = NumberFormat(anImageStruct.height / ratioDivider)>
<!--- perform the resize --->
<cfimage action="resize"
height="#height#"
width="#width#"
source="#TempImage#"
name="ScaledImage"
quality="1"
destination="#cffile.ServerDirectory#/thumb_#cffile.ServerFile#"
overwrite="true"/>
<!--- write the image out to the browser --->
<p>Resized Image (<cfoutput>#width# X #height#</cfoutput>)<br/>
<cfimage action="WriteToBrowser" source="#ScaledImage#"></p>
<cfelse>
<!--- the form to upload an image --->
<cfform action="#cgi.script_name#"
method="post"
enctype="multipart/form-data"
name="theForm">
<cfinput type="file" name="FileUpload">
<cfinput name="submit" type="submit" value="Submit">
</cfform>
</cfif>
Here's the output:

A couple of things to note here. I have tried and tried to get the cfimage tag to overwrite an image that already exists with no success. The workaround seems to be to just name the image something else, I've added thumb_ as a prefix to any thumbnail images. Secondly, you may want to capture which file types you are willing to accept. CFImage is limited to certain image formats that vary from OS to OS. You can output the file types your system can handle by dumping the getReadableImageFormats() function.





Loading....