With a little side of applesauce...

Saturday, July 24, 2010

Coldfusion - Displaying images from a database

I have found that serving images housed in a database is made easier by using a mixture of Coldfusion and jQuery/JSON. Here is how I did it:

1. Create a CFC with the setStudentImage function. This calls another CFC which simply returns a query with all matching user images, loops through the results base64-encodes the image, adds it to the array, then returns the array. (We need to base64-encode the image, so that we can hand it off to JSON, (Is this really needed? I haven't checked, as I notice that I am returning an array to Javascript, and not JSON)).

    <cffunction name="setStudentImage"
hint="returns image via email

@return result array">
<cfargument name="email" type="string" required="false" default="">

<!--- Define variables --->
<cfset var data="">
<cfset var result = ArrayNew(1)>

<!--- do search --->
<cfset userObject = cfcCard.getImageByEmail( '#email#' )>

<!--- build result array --->
<cfloop query = "userObject">
<cfset base64Img = ToBase64( userObject.IMAGE )>
<cfset ArrayAppend( result, '#base64Img#')>

<cfreturn result>

2. We create our cfajaxproxy, and the Javascript to call Coldfusion for the image, then modify our img tag to display our image:
<cfajaxproxy cfc="#Application.cfcPath#.Card" jsclassname="o">

<script type="text/javascript">
function callSetStudentImage( useremail ) {
var inst = new o();
var result = inst.setStudentImage( String( useremail ) ) ;

return result;
function getStudentInfo( magstrip ) {
var userimg = callSetStudentImage( useremail );
if (userimg != "") {
$( '#myimg' ).attr( 'src', 'data:image/*;base64,' + userimg ).resize({maxHeight: 150, maxWidth: 200});

3. Ben Forta's method for displaying images from a database here, worked well for everything, except for size manipulation, so I turned to a great jQuery plugin, jQuery Resize Image Plugin, to do the resizing for me:
 $( '#myimg' ).attr( 'src', 'data:image/*;base64,' + userimg ).resize({maxHeight: 150, maxWidth: 200});

The only issues that I have now, are displaying the base64-encoded images in Google Chrome, (for some reason), and Firefox 4 Beta 1...

No comments: