Loading an image via the <img> tag using ColdFusion

· 32 Comments · in Coldfusion, More

I wrote a basic routine to accomplish this awhile back using <CFImage> and decided to revisit it.

I found out it needed major rework!

There were all types of exceptions dealing with transparent png and gif files.

After spending 2+ days on it, I believe the following is a solid solution.

Usually you just have a reference to an image source in a database. Almost all sites have their images on a CDN and the code was written with this in mind.

What if you want to create a thumbnail of that original image instead of serving the full image and using CSS to resize? Or having to create multiple thumbnail files?

This is a dynamic way to create a thumbnail or serve the full-size image without having to run ColdFusion on the calling page.

Basically, we will call a .cfm file as the source of an <img> tag, passing it parameters.

There’s info and examples out there to accomplish this but none have fully addressed the issues I was encountering.

Some transparent gif/png files would render correctly, others not. Files in jpg format would display at a lower quality than intended.

Code will work and tested with the following formats:
gif
transparent gif
grayscale gif
png
transparent png
grayscale png
jpg

I wrote this as a simple CFM so you can grab and test quickly, feel free to convert to a CFC.

The biggest issue I encountered was colorSpace on transparent files. The images would display in a format that did not use the color profile intended.

Then I found a post by Raymond Camden here, describing how to access the underlying Java colorSpace – simply brilliant!

I re-purposed some of that code to apply the CS_sRGB generic colorSpace to transparent images using the W3 recommended colorSpace listed here.

The code resizes an image, if specified – and slightly sharpens the image if resized.

You can resize the image downward, upward or serve the image at it’s original dimensions.

There is no compression, all images are served in “png” format, to allow for correct colorSpace and quality.

There is a slight delay as images are processed and loaded, but it’s minimal. This is the cost for being dynamic/virtual. :) Files in jpg format load much faster than gif or png. Transparent gif files take the longest.

Code works with files in png, jpg and gif format. Animated gif files are not supported, that’s a <CFImage> limitation. Though it will show the first frame of the animated gif file.

To make this completely virtual, I took advantage of CF 9+ Virtual File System(RAM Disk). You can write files to memory and then read them back in. The code writes out files, reads them and then immediately deletes them from memory.

Files are displayed with the correct aspect ratio, calculated using the width parameter sent to the cfm.

To serve an image you pass an image parameter and a width parameter(pixels):

<img src="getImage.cfm?i=http://mycdn.com/borg_queen.png&w=100">

If you want to serve the image with original dimensions, do not send the width parameter:

<img src="getImage.cfm?i=http://mycdn.com/borg_seven.jpg">

If you want to create a transparent 1×1 tracking pixel:

<img src="getImage.cfm?w=1">

* If a requested image does not exist, a transparent image will be created with the dimensions calculated by the width parameter.

I did run into an issue with IE 8(big surprise), where the image dimensions were not recognized when the image loads. Here is the CSS fix:

img {
	width:auto;
	height:auto;
}

You can also create an image tag dynamically using jQuery:

var _iPath = "i=http://path_to_my/image.jpg";
var _w = "w=100";
var _i = $("<img/>").attr("src","getImage.cfm?" + _iPath + "&" + _w);

* If you are trying to serve an image from Amazon S3 and it does not render, the image needs to be made “public”. If you have a policy on the bucket that holds the image, it should still be protected.

ColdFusion

<cftry>
<cfparam name="URL.i" default="">
<cfparam name="URL.w" default="">

<cfif Trim(URL.i) NEQ "">

	<!--- grab image --->
	<cfimage name="imgObj" source="#Trim(URL.i)#">

	<!--- if not an image - create blank image --->
	<cfif NOT IsImage("#imgObj#")>
		<cfthrow>
	</cfif>
	
	<!--- if image width or URL.w LTE 1, create 1x1 --->
	<cfif (Trim(URL.w) NEQ "" AND (URL.w LTE 1)) OR (ImageGetWidth(imgObj) LTE 1)>
		<cfset URL.w = 1>
		<cfthrow>
	</cfif>
	
	<!--- if .png or .gif - fix colorspace --->
	<cfif Right(Trim(URL.i),4) IS ".png" OR Right(Trim(URL.i),4) IS ".gif">
		<cfset imgFromBuffer = imageGetBufferedImage(imgObj)>
		<!--- apply generic colorSpace --->
		<cfset gCS = createObject("java","java.awt.color.ColorSpace").CS_sRGB>
		<cfset colorProfile = createObject("java","java.awt.color.ColorSpace").getInstance(gCS)>
		<cfset convert = createObject("java","java.awt.image.ColorConvertOp").init(colorProfile,javaCast("null",""))>
		<cfset newImage = convert.filter(imgFromBuffer, javaCast("null",""))>
		<cfset imgObj = imageNew(newImage)>
	</cfif>
	
	<!--- CFCONTENT needs file ext so we have to write/read/delete file --->
	<!--- create unique filename --->
	<cfset imgPathFilename = "ram:///" & CreateUUID() & ".png">
	<!--- write image to ram --->
	<cfimage action="write" source="#imgObj#" destination="#imgPathFilename#">
	<!--- read image from ram --->
	<cfimage name="imgObj" source="#imgPathFilename#">
	<!--- delete image from ram --->
	<cffile action="delete" file="#imgPathFilename#">

	<!--- scale/sharpen only if width request --->
	<cfif Trim(URL.w) GT 1>
		<!--- scale image --->
		<cfimage
			name="imgObj" 
			source="#imgObj#"
			action="resize"
			width="#Trim(URL.w)#"
			height=""
		>
		<!--- sharpen image --->
		<cfset ImageSharpen(imgObj,1.5)> 
	</cfif>
	
	<!--- serve image --->
	<cfcontent type="image/png" variable="#imageGetBlob( imgObj )#">

<cfelse>
	<cfthrow>
</cfif>

<cfcatch>
	<!--- on error create a transparent image --->
	<cfif Trim(URL.w) IS "">
		<cfset URL.w = 1>
	</cfif>
	<cfset blankImg = ImageNew("",Trim(URL.w),Trim(URL.w),"argb") />
	<!--- CFCONTENT needs file ext so we have to write/read file --->
	<!--- create unique filename --->
	<cfset imgPathFilename = "ram:///" & CreateUUID() & ".png">
	<!--- write image to ram --->
	<cfimage action="write" source="#blankImg#" destination="#imgPathFilename#">
	<!--- read image from ram --->
	<cfimage name="blankImg" source="#imgPathFilename#">
	<!--- delete image from ram --->
	<cffile action="delete" file="#imgPathFilename#">
	<cfcontent type="image/png" variable="#imageGetBlob( blankImg )#">
</cfcatch>
</cftry>

See the full working example here.

Great books are available on ColdFusion here.

Tested in:
ColdFusion 9+
FF 3.6+, Safari, Chrome, IE8+, iOS

This entry was posted in Coldfusion, More and tagged , .
Bookmark the permalink.

32 Responses to Loading an image via the <img> tag using ColdFusion

  1. scrapeblogs says:

    I am extremely impressed together with your writing skills and also with the structure on your blog. Is that this a paid subject or did you customize it yourself? Either way stay up the nice quality writing, it’s rare to look a great weblog like this one nowadays.

  2. clarke ulmer says:

    Thanks for the kind comments. Customized entirely by me :)

  3. I’d constantly want to be update on new posts on this internet site , bookmarked ! .

  4. Tora Melling says:

    Great web site you have got here.. It’s hard to find good quality writing like yours these days. I seriously appreciate individuals like you! Take care!!

  5. Denice says:

    This is especially useful if the person you’re inquiring about has a less than common name.
    I set an example of such information to demonstrate the formatting of a typical contact page as shown below:
    . Incompatibility: Rails’ structured and organized approach can be its strength as well as
    weakness in terms of flexibility and compatibility.

  6. Cornelius says:

    The website will also serve as a portal for all things convention related, from a countdown clock to information on logistics, credentials, media walkthroughs and housing.
    No software to buy, no code to learn, all you need is to be a little Internet
    savvy and know how to click your mouse. I discovered
    the way to make money on the internet.

  7. Layne says:

    Make money on autopilot is available for all
    of us. Not only do you want lots of people to visit your website but you also want your
    visitors to stay on your site and see if the deal is worthwhile by simply checking out your site.
    A money making attitude plus a money making opportunity almost always
    result in a money making reality.

  8. Evangeline says:

    Most of the card dealers sell their cards online through
    websites that specialize in international calling cards.
    The website navigation should cater to both the users and the search engine bots.

    You will also find 30 free tools, and software programs to help you build a successfull Internet
    Business.

  9. Leonore says:

    When you bike France you create the opportunity to travel on your own or be part of other guests to partake in a bicycle tour.
    ‘ A vehicle overtakes a bicycle and does not allow the bicycle enough space to safely pass and
    caused the cyclist to fall off the bike. This mount can be installed either vertically or horizontally, depending on the preference of
    the cyclist.

  10. Matilda says:

    Many vintage cycling clothing items have reappeared after disappearing for several years.
    As your child migrates to cycling on the road, they will be at increased risk and
    a few new guidelines may help:It is important to note
    that you are not nearly as visible as cars and not all cars behave perfectly.
    The first time you need to use it, you’ll be happy you bought it.

  11. Para ser justos preparo una segunda entrada con las marcas que
    no aparecen en este.

  12. Levi says:

    En nuestros documentales de bodas, os entregamos todas las fotografías
    que disparemos durante el día.

  13. It’s enormous that you are getting thoughts from this paragraph as well as
    from our argument made at this place.

    Lisätietoa: http://juegos-gratis-ya.com/blog/groups/kesaksi-kengat-1513818775/

  14. I think this is among the most vital info for me. And i’m happy reading your article.
    But wanna commentary on some common things, The website
    taste is perfect, the articles is really excellent : D.
    Just right activity, cheers

  15. This paragraph provides clear idea in support of the new users of blogging, that actually how
    to do blogging.

  16. Phillip says:

    After exploring a number of the articles on your blog,
    I seriously appreciate your technique of writing a blog.
    I book marked it to my bookmark site list and will be checking back soon. Take a look
    at my website too and let me know what you think.

  17. I like what you guys tend to be up too.
    Such clever work and reporting! Keep up the wonderful works guys I’ve incorporated
    you guys to blogroll.

  18. Fotógrafo de la Guardia Real de la Casa de S.M.
    El Rey en mil novecientos noventa y ocho, acumula
    una gran experiencia en todo tipo de fotografías y actualmente efectúa,
    entre otros muchos trabajos, documentales de boda en la capital española con abundantes registros para
    que cada pareja de novios decida qué estilo desea imprimir a su álbum.

  19. I’ve learn several good stuff here. Definitely
    price bookmarking for revisiting. I wonder how a lot attempt you place to make the sort of excellent informative
    web site.

    my website jobs new zealand

  20. Socio fundador de Objetivo Valencia Fotografía,
    donde imparte cursos y talleres de fotografía, realiza viajes fotográficos y fotografía de estudio.

  21. Jayson says:

    Aparte de otros abundantes conocidos dispara largo
    de su tiempo de vida, ella es conocida por hacer una sesión de fotos con John Lennon para
    Rolling Stone.

  22. Me da mucha curiosidad el verme algún día con ellas

    puestas..

  23. Nice blog right here! Also your site loads up very
    fast! What web host are you the usage of? Can I get your associate hyperlink to your host?

    I wish my web site loaded up as quickly as yours lol

  24. Discont says:

    Unquestionably believe that that you said. Your favorite reason appeared to be
    at the net the easiest factor to have in mind of.
    I say to you, I certainly get irked while folks think about concerns that they plainly don’t recognise about.
    You controlled to hit the nail upon the highest and outlined
    out the entire thing without having side effect , other folks can take a signal.
    Will likely be back to get more. Thanks

  25. Timothycen says:

    buy photoshop cs5 download microsoft office discount for teachers Autodesk Infrastructure Design Suite Ultimate 2016 where can i buy microsoft office 2010 for mac student discount microsoft office for mac uk

  26. LastDolores says:

    I see you don’t monetize your blog, don’t waste your traffic, you can earn additional bucks every month because you’ve got
    high quality content. If you want to know how to make extra money, search for:
    Mertiso’s tips best adsense alternative

  27. This piece of writing presents clear idea
    in favor of the new users of blogging, that genuinely how to do
    running a blog.

  28. Gold king says:

    Attractive section of content. I just stumbled upon your web site and in accession capital to
    assert that I acquire in fact enjoyed account your blog posts.

    Anyway I will be subscribing to your augment and even I achievement you access consistently fast.

  29. best bitcoin miner for android 2018 says:

    Btc 1AHRQRgR7Hn6MNQEVzzHYCLWAJKjGPP2gV

  30. example says:

    Please let me know if you’re looking for a article author for your site.
    You have some really great posts and I believe I would be a good asset.
    If you ever want to take some of the load off, I’d absolutely love to write some articles for your blog in exchange for a link back to mine.
    Please send me an email if interested. Many thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

To include code in your comment: Paste your code in the comment form, select it and then click the language link button below. This will wrap your code in a <pre> tag(or shortcode) and format it when submitted.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">