Monday, January 26, 2009

How to Convert Blob Image to Image File

To convert blob back to image file, first, execute a select statement that would retrieve the blob from the database:

$strsql="SELECT blobfile FROM table";
$sql=sqlsrv_query($conn, $strsql);
$row = sqlsrv_fetch_array($sql);

Then, create a temporary file and write the blob record:

$temp = tempnam("http://pathtofile", "tmp.bmp");
$handle = fopen($temp, "w");
$fwrite($handle, $row[1]);
$fclose($handle);
sqlsrv_free_stmt($sql);

You can now output this image on your page, or report, or download it using headers.

NOTE: this example uses PHP and MS SQL 2005. You can substitute the sql functions for MySQL.