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:
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:
<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!


<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.