Tuesday, January 27, 2009

Binary Object Decoding, Transmitting, Encoding Using Coldfusion

As we start delving into storing binary objects (pdf's, images etc) this post will help you encode, decode and/or transmit the data you are working with. Now I am coming from the perspective of a CF developer so you will need to adapt where need be for environment.

We start with a Binary Object (an image).

1. Binary Object
2. Convert it to base64 for transmitting via xml or another HTTP method
---> a. CF method: toBase64(binaryObj)
3. Receiver takes the data and encodes it back to a binary object
---> a. CF method: toBinary(base64String)


<cfquery name="q" datasource="#REQUEST.mysqldsn#">
SELECT binaryColumn <!--- This column is a longblob --->
FROM mytable

<!--- View the data from the DB call --->
<cfdump var="#q#">

<!--- Create a way to view the binary object --->
<cfset myImg1 = ImageNew(q.document)>
<cfimage action="WRITETOBROWSER" source="#myImg1#">

<!--- Now convert the binary object from the DB to a base64 string --->
<cfset doc = tobase64(q.document)>
<!--- Display the base64 string --->

<!--- Convert the base64 string to a binary object --->
<cfset doc = toBinary(doc)>

<!--- Dump the converted base64 to a binary object to view it --->
<cfdump var="#doc#">

<!--- Create a way to view the binary object --->
<cfset myImg2 = ImageNew(doc)>
<cfimage action="WRITETOBROWSER" source="#myImg2#">

Note: Be sure you change your CFADMIN longblob size limits if you need to store large binary objects. Otherwise the data will be truncated.