Skip to main content
Ben Nadel at cf.Objective() 2013 (Bloomington, MN) with: Brad Wood
Ben Nadel at cf.Objective() 2013 (Bloomington, MN) with: Brad Wood

Styling The ColdFusion 8 WriteToBrowser CFImage Output

By
Published in Comments (22)

The ColdFusion 8 has some amazing functionality, one feature of which is being able to write an image to the browser as an inline IMG tag:

<cfimage
	action="writetobrowser"
	source="./mud_monster.jpg"
	/>

The problem with this is that it writes the IMG tag to the browser and doesn't give you any ability to add your own IMG attributes, including CSS or STYLE. This may or may not be a problem for people, but it would be nice to have access to the tag data.

This dilemma is actually fairly easy to overcome. The CFImage tag, in addition to creating the image object and saving to the file system, is really just writing to the page's content buffer, which is then flushed to the client along with everythign else. As such, we can intercept the content buffer write, modify it in any way we want, and then write the new IMG tag to the page's content buffer.

I have created ImageWriteToBrowserCustom(), a ColdFusion user defined function that takes your ColdFusion 8 image object and additional attribute values and writes the IMG tag for you. Here's what it might look like:

<html>
<head>
	<title>ColdFusion 8 WriteToBrowser() Modification</title>
	<style type="text/css">

		img.frame {
			border: 2px solid #660000 ;
			}

	</style>
</head>
<body>

	<!--- Read image into memory. --->
	<cfimage
		action="read"
		source="./mud_monster.jpg"
		name="objImage"
		/>

	<!--- Write to browser with custom attributes. --->
	<cfset ImageWriteToBrowserCustom(
		Image = objImage,
		Alt = "Mud Monster - She So Crazy!",
		Class = "frame",
		Style = "border-width: 10px ;"
		) />

</body>
</html>

Notice that ImageWriteToBrowserCustom() is taking the image that we read in via CFImage as well as the ALT, CLASS, and STYLE attributes. If we now look at the source code of the rendered page, we will get the following image tag (I have wrapped it for easy viewing):

<img
	src="/CFFileServlet/_cf_image/_cfimg527766746223564434.PNG"
	alt="Mud Monster - She So Crazy!"
	class="frame"
	style="border-width: 10px ;"
	/>

The user defined function that accomplishes this is actually fairly simple and just traps the IMG tag output using ColdFusion's CFSaveContent tag:

<cffunction
	name="ImageWriteToBrowserCustom"
	access="public"
	returntype="void"
	output="true"
	hint="Writes the image to the browser with additional attributes.">

	<!--- Define arguments. --->
	<cfargument
		name="Image"
		type="any"
		required="true"
		hint="The ColdFusion image object that you are writing to browser."
		/>

	<cfargument
		name="Alt"
		type="string"
		required="false"
		default=""
		hint="The ALT attribute value to apply to the image."
		/>

	<cfargument
		name="Class"
		type="string"
		required="false"
		default=""
		hint="The CSS class to apply to the image."
		/>

	<cfargument
		name="Style"
		type="string"
		required="false"
		default=""
		hint="The STYLE attribute value to apply to the image."
		/>

	<cfargument
		name="Height"
		type="string"
		required="false"
		default=""
		hint="The HEIGHT attribute value to apply to the image."
		/>

	<cfargument
		name="Width"
		type="string"
		required="false"
		default=""
		hint="The WIDTH attribute value to apply to the image."
		/>

	<cfargument
		name="Border"
		type="string"
		required="false"
		default=""
		hint="The BORDER attribute value to apply to the image."
		/>


	<!--- Define the local scope. --->
	<cfset var LOCAL = {} />


	<!---
		Write the image to the browser. This is really just
		creating the image and then writing to the buffer.
		All we have to do is intercept the buffer write.
	--->
	<cfsavecontent variable="LOCAL.Output">
		<cfoutput>

			<!--- Write image tag. --->
			<cfimage
				action="writetobrowser"
				source="#ARGUMENTS.Image#"
				/>

		</cfoutput>
	</cfsavecontent>

	<!---
		First, delete any existing attributes that we might
		be using (so that we can just add new ones).
	--->
	<cfset LOCAL.Output = LOCAL.Output.ReplaceAll(
		"(?i) (alt|class|style|height|width|border)=""[^""]*""",
		""
		) />

	<!---
		Now that we have an image with Just the SRC
		attribute, we can go about adding our attributes.
		First, chop off the trailing slash.
	--->
	<cfset LOCAL.Output = LOCAL.Output.ReplaceFirst(
		"\s*/?>\s*$",
		""
		) />

	<!---
		Loop over the arguments to see if we need to
		add them to the tag.
	--->
	<cfloop
		index="LOCAL.Key"
		list="alt,class,style,height,width,border"
		delimiters=",">

		<!--- Check for a passed-in value. --->
		<cfif Len( ARGUMENTS[ LOCAL.Key ] )>

			<!---
				Append this argument to the output and a
				key-value attribute.
			--->
			<cfset LOCAL.Output &= (
				" " &
				LOCAL.Key &
				"=""" &
				ARGUMENTS[ LOCAL.Key ] &
				""""
				) />

		</cfif>

	</cfloop>

	<!--- Write the image tag to the output. --->
	<cfset WriteOutput( LOCAL.Output & " />" ) />

	<!--- Return out. --->
	<cfreturn />
</cffunction>

I am sure (*hoping*) that eventually ColdFusion 8 will give us the ability to control the attributes of the rendered IMG tag, but for now, this seems like a decent solution. The one thing I don't like about it is that it requires the Output attribute of the CFFunction tag to be true; I really don't like having output in a function call, but I also didn't want to return a value since CFImage / WriteToBrowser doesn't return any values (and I wanted to keep in sync with that style.

Want to use code from this post? Check out the license.

Reader Comments

15,902 Comments

While I didn't do this in the demo, this could probably be made more flexible by not actually defining the argument tags, but rather looping over the arguments and created name-value attributes for anything NOT named "Image". This way, you could just about add any attribute you wanted to (ex. onclick, onload).

15,902 Comments

@Rupesh,

Yeah, not a huge deal, but down the road, it would definitely be cool. Especially since I think I remember saying Ben Forta saying that all the AJAX stuff produces XHTML compliant code, and I think technically, all images need height/width attributes to be "standards compliant" (maybe).... not that that really matters to me so much, but just another selling point.

5 Comments

Don't forget that there are often many more attributes that could be used (like id="uniqueVal"). A simple solution might be to offer an attribute called xcode (or whatever) where it just adds the entire value to the resulting img tag as attribute=value pairs.

example:

xcode='alt="My IMage" id="myImage" class="imgRight"'

Just a thought.

4 Comments

Once again great work Ben. But I have the problem to add attributes to a CF generated captcha image. With captcha u can not use the name attribute to cfimage tag. So I thought about using cfsavecontent, which returns one of the most weird errors:

The png" alt="" height="40" width="140" /> image format is not supported on this operating system. Use GetReadableImageFormats() and GetWriteableImageFormats() to see which image formats are supported.

I created a function for this:

<cffunction
name="writeCaptcha"
displayname="writeCaptcha"
hint="I will output the captcha image"
returntype="any">

<cfargument name="strCaptcha" type="string" required="false">

<cfset var ret = "">

<cfsavecontent variable="ret">

<cfoutput>

<cflock name="captcha" type="exclusive" timeout="20">

<cfimage
action="captcha"
height="40"
width="140"
text="#arguments.strCaptcha#"
difficulty="medium"
fonts="verdana,arial,times new roman,courier"
fontsize="20"
/>

</cflock>

</cfoutput>

</cfsavecontent>

<cfreturn ret/>
</cffunction>

Do you have any other suggestion, or a workaround so I can use your ImageWriteToBrowserCustom() function on captcha images?

15,902 Comments

@Alexander,

That's a funky error. I don't believe I tried to use this with CAPTCHA. If I can get some time, I'll take a looksee.

2 Comments

Just wanted to let you know that this code greatly helped me. On many occasions I have gotten frustrated with my non-functioning code, turned to Google for help and your site has always had an answer. Thank you!

4 Comments

Hi Ben, hi Matt,

now that I received your message, Matt, I was wondering why the hell is that code not working for me. So I tried this code once again on my personal machine at home and...well..it is working here perfectly. Strange, because both machines (company and at home are same). I guess I will look out for some hotfixes, that may be applied on my machine, already.

Thank you for getting me back on this.

Kind regards
Alex

14 Comments

Great work yet again Ben! Whilst I didn't use this whole code, I copied some of your regex code for a similar problem with the lack of an alt attribute and unescaped ampersands in CFIMAGE for Railo 3.1.

Thanks!

:)

3 Comments

Great work! I use a jQuery solution that has worked quite well. The example uses a real image file and a CF-created one.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<style>
.myImage { border:4px solid red; };
</style>
<cfimage name="cImg1" source="pic.jpg">
<cfset cImg2 = ImageNew("","100","100","grayscale")>
<span class="imgAddClass"><cfimage action="writeToBrowser" source="#cImg1#" format="jpg" quality="1"></span>
<span class="imgAddClass"><cfimage action="writeToBrowser" source="#cImg2#" format="jpg" quality="1"></span>
<script>$(".imgAddClass img").addClass("myImage").attr("alt","This is my image");</script>

2 Comments

I did this by just adding the attributes directly to cfimage:

<cfimage action="writeToBrowser" source="#image#" style="border: 1px solid grey" />

Is this not a good idea?

15,902 Comments

@Jye,

At the time, I had no idea that you could add arbitrary attributes to the CFImage tag for this action. Your way is definitely easier; this is also the way I have started using.

2 Comments

Gotcha. Just wanted to make sure I wasn't circumventing some ColdFusion restriction. Thanks for the great blog.

15,902 Comments

@Jusuf,

No problem. And just in case you missed it in some of the other comments, you can actually add additional, arbitrary attributes to the CFImage tag (ex. border, style, class). I discovered that only after this blog post. Example:

<cfimage action=writetobrowser" class="headshot" />

This just makes things so easy.

2 Comments

For Railo users
-------------

Railo doesn't allow you to set additional arbitrary attributes to the CFImage tag but it has a passthrough attribute.

<cfimage passthrough="class=thumbnail" source="#myimage#" action="writeToBrowser">

1 Comments

having trouble displaying an image where I want to display it.
<CFTABLE QUERY="getQuality" BORDER COLHEADERS HTMLTABLE>
<cfif #SOURCE_LEVEL# eq 1>
<cfset clevel = "GREEN">
<!--- This example shows how to create a ColdFusion image from a GIF file, resize it, and
then display it in the browser as a PNG image. --->
<cfimage source="new/greencircle.gif" action="read" name="smcircle">
<cfimage source="#smcircle#" action="writeToBrowser">
<cfelseif #SOURCE_LEVEL# eq 2>
<cfset clevel = "YELLOW">
<!--- This example shows how to create a ColdFusion image from a GIF file, resize it, and
then display it in the browser as a PNG image. --->
<cfimage source="new/yellowcircle.gif" action="read" name="smcircle">
<cfimage source="#smcircle#" action="writeToBrowser">
<cfelse>
<cfif #SOURCE_LEVEL# eq 3>
<cfset clevel = "RED">
<!--- This example shows how to create a ColdFusion image from a GIF file, resize it, and
then display it in the browser as a PNG image. --->
<cfimage source="new/redcircle.gif" action="read" name="smcircle">
<cfimage source="#smcircle#" action="writeToBrowser">
</cfif>
</cfif>
<cfset slevel = #smcircle#>
then trying to display slevel

I'm able to display clevel but not slevel

1 Comments

I'm trying to figure out how to paste an image directly into a field on the ColdFusion page form rather than using upload from file.My users use snagit to edit screen shot captured and would like to paste that image to a form they fill out then we process as blob and save in Database. I'm new to ColdFusion development but well conversant with other languages.

Thanks,
Dave

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel