Tuesday, April 16, 2013

Displaying an image stored in MSSQL via Quercus PHP

I know, not exactly thrilling stuff here, but I figured I'd throw a bone to anyone else out there in the interwebs who might struggle in like manner.

I'm not entirely (or even remotely) sure why, but the version of Quercus I'm using (4.0.25) is returning (using PDO for database interaction) my image column (type: Image, MSSQL 2008) as a hex encoded string (instead of binary which is what I'd expect). That means, all the example code out there in the interweb that instructs you to return an image thusly was not working for me:

No Worky
<?php

//  PDO stuff 
//  ...

$image = $results['Image'];
header ('Content-Type: image/jpg');
echo $image;

?>

Once I realized that php was handing me back the image data as a hexadecimal string I just had to figure out how to convert that to a binary string. PHP versions 5.4 and later have a function named hex2bin but alas Quercus 4.0.25 implements PHP 5.3.2. Have no fear; pack to the rescue! My new and improved (as in working) code shown below.

Worky
<?php

//  PDO stuff 
//  ...

$image = $results['Image'];
header ('Content-Type: image/jpg');
echo pack('H*',$image);

?>

Next up.... something else (hopefully a little less stuffy)

No comments:

Post a Comment