Transforming SQL binary data to usable code with Coldfusion

Although I prevent using binary data inside database tables, I know have a project where a company logo for each account in the database is stored inside the database as a binary object.

I use this code to get it out. Read on...

First of all, I get the binary object from the database:

<cfquery datasource="#application.DSN#" name="GetCompany">
SELECT binaryLogo
FROM tblCompany
WHERE autoID = #request.cID#
</cfquery>

<cfset session.binaryLogo = GetCompany.binaryLogo >
<img src="accountcard-image.cfm" hspace="20" vspace="20">

I put the binary logo data in a session variable, so I can use it as a header on more pages than one, and it's also accessible from the next page.

Then I created a page "accountcard-image.cfm", that contains this code:

<cfsetting enablecfoutputonly="yes">
<CFHEADER NAME="Pragma" VALUE="no-cache">
<CFHEADER NAME="Cache-Control" VALUE="no-cache">

<cfif toString(session.logocode) contains "JFIF">
   <cfset type="JPEG">
<cfelse>
   <cfset type="GIF">
</cfif>

<cfset currentpath = expandPath('.')&"\Images\Temporary\">

<cffile action="write" file="#currentpath#TempIMG.#LCase( TYPE )#" output="#session.binaryLogo#" addnewline="No">
<CFCONTENT TYPE="image/#LCase( TYPE )#" FILE="#currentpath#TempIMG.#LCase( TYPE )#" DELETEFILE="YES">

<cfsetting enablecfoutputonly="no">

I check the image type (which can only be .GIF or .JPEG in my logo-example, because of the way the database-software has been set up) by parsing the binarycode and looking for the JFIF header.

I've created a temporary folder inside my images folder. This folder should normally stay empty, but is used as a directory where the images are stored during the page request. The CFCONTENT has the "DELETEFILE" attribute set, so when the image is served, it get's deleted immediately.

Presto! You've got a binary database to image converter!

Comments
Ben Nadel's Gravatar I have never used binary data in a database before, but I have been tempted to look into it - it just seems so convenient to not have to depend on two systems for data (file and database). Anyway, just a thought - you probably don't have to write the binary to file first; you can't probably just stream it:

<cfcontent
type="image/#LCase( TYPE )#"
variable="#session.binaryLogo#"
/>

I have never done this with a database blob, but as long as you are streaming data with CFContent, I think it might be faster to go this route.
# Posted By Ben Nadel | 8/31/07 2:26 PM

BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.