Cloud Photo

Azure Data Architect | DBA

BLOB Image Data To Disk in Railo/ColdFusion

A recent need to download all the images stored as BLOB (Binary Large OBject) from a database lead me back to ColdFusion. Using the toBase64() and imageReadBase64() functions along with the cfimage tag I was able to create a page that displays the images in the database and writes them to a file on the server.

First, we’ll use CFQUERY to select the data out of the database. In my example, I set a maxrows so that we can export a manageable number of files at a time.

<cfquery datasource=imgDS name=qImages maxrows=5>
SELECT img_id as id, img_data as img FROM imagesTable
</cfquery>

 

Next, we use CFOUTPUT to output the query.

<cfoutput query=qImages>

 

Then, an img tag with data as the source displays the image on the page. The toBase64() function converts the BLOB to a stream that the browser can interpret as image data.

<img src="data:image/*;base64,#toBase64( img )#" height="150" />

 

Next, the myImage variable stores the image from the base64 stream.

<cfset myImage = imageReadBase64(toBase64( img ))>

 

The CFIMAGE tag takes the contents of the myImage variable and writes it to disk. For this project, I knew that all the images were JPGs. If your database doesn’t store file names or mime types for each record, you may have a more difficult task.

<cfimage action="write" source="#myImage#" destination="c:\saved_images\#id#.jpg">

 

Finally, we close the CFOUTPUT.

</cfoutput>

 

Here is the entire code all put together for you.

<cfquery datasource=imgDS name=qImages maxrows=5>
SELECT 
 img_id as id
 ,img_data as img
FROM imagesTable
</cfquery>
<cfoutput query=qImages>
 <img src="data:image/*;base64,#toBase64( img )#" height="150" />
 <br>
 <cfset myImage = imageReadBase64(toBase64( img ))>
 <cfimage action="write" source="#myImage#" destination="#id#.jpg">
</cfoutput>

Leave a Reply