CFML Image Place holder Custom Tag

Sep 26 2011

CFML Image Place holder Custom Tag

Posted by AJ Mercer at 3:09 PM CFML | ColdFusion | Railo

I saw a tweet today from @modius about an Image Placeholder service and I thought this should be pretty easy to do with CFML - and it was.

 

Here is the code for a custom tag

<cfsetting enablecfoutputonly="true">
<cfparam name="attributes.width" default="350">
<cfparam name="attributes.height" default="150">
<cfparam name="attributes.backgroundcolour" default="black">
<cfparam name="attributes.text" default="">
<cfparam name="attributes.fontSize" default="36">
<cfparam name="attributes.fontColour" default="white">
<cfparam name="attributes.returnType" default="image" > <!--- hint="image|tag" --->
<!--- font hard-coded to make calculating centre easier ;-) --->
<cfset attr = { font="Courier New", size=attributes.fontSize, style="normal"}>
<cfset top = Round((attributes.height + attr.size) / 2) >
<cfset left = Round(((attributes.width - (Len(attributes.text) * attr.size*0.6)) /2) ) />
<cfset imgPlaceHolder = imageNew("",attributes.width,attributes.height,"rgb",attributes.backgroundcolour)>
<cfset ImageSetDrawingColor(imgPlaceHolder,attributes.fontColour)>
<cfset imageDrawText(imgPlaceHolder, attributes.text, left, top, attr)>

<cfif attributes.returnType EQ "Tag">
<cfoutput><img src=""><img src="data:image/*;base64,#toBase64( imgPlaceHolder )#"/> </cfoutput>
<cfelse>
<cfoutput><cfimage action="writeTobrowser" source="#imgPlaceHolder#"></cfoutput>
</cfif>
<cfsetting enablecfoutputonly="false">

 

And to use it to return image to browser
eg /index.cfm?width=600&height=400&fontSize=60&text=hello,+Webonix!

<cfparam name="URL.width" default="350">
<cfparam name="URL.height" default="150">
<cfparam name="URL.backgroundcolour" default="black">
<cfparam name="URL.text" default="">
<cfparam name="URL.fontSize" default="36">
<cfparam name="URL.fontColour" default="white">

<cf_imagePlaceHolder 
width="#URL.width#"
height="#URL.height#"
backgroundcolour="#URL.backgroundcolour#"
fontColour="#URL.fontColour#"
fontSize="#URL.fontSize#"
text="#URL.text#"
>

Or as an image tag in you code

<cf_imagePlaceHolder 
width="200"
height="200"
backgroundcolour="##e0e0e0"
fontColour="black"
fontSize="12"
text="image goes here"
>

 

To make the text positioning calculations easiy, i have hard-coded a mono-space font. But using Ben Nadel's ImageUtils you could pimp this out some more.

Code examples taken from the weblog revolution.