How to serve pictures from a database

You are building a web application for a Human Resources department. One part of this application is the display of an employee profile, including a photograph. All this information is stored in a database.

How do you extract the picture of an employee for display on a web page?

Listing 1 presents the script to create the employee table on a Sybase SQL Anywhere database.

CREATE TABLE employee (
   id          NUMERIC(12,0)  NOT NULL,
   first_name  VARCHAR(50)    NULL,
   last_name   VARCHAR(50)    NULL,
   picture     LONGVARBINARY  NULL

Listing 2 shows how to use the img tag at our advantage to call a dynamic web page as the source of the picture. Remember that the src attribute is not limited to static files. In fact, it can accept anything as long as it returns a valid picture.

<img src="picture.cfm?id=100" />

Listing 3 shows how to use the <cfcontent> tag to send a different content type back to the browser than the default <text/html>. In this example, the response will be a bitmap image extracted from a BLOB field in a database.

<cfquery name="MyPicture" datasource="MyDataSource">
   select picture
   from person
   where id =
<cfcontent type="image/x-ms-bmp" variable="#MyPicture.picture#"> 

This question was written by Philippe Randour
It was last updated on May 29, 2007.


Display and Layout


comments powered by Disqus