|
|
Title |
Extract a GIF image from a SQL Server database for display in a web browser.
|
Summary |
Here we will extract a BLOB (representing a GIF image) from a SQL server database and display it in a web browser and embedded in a web page. This will be done without saving the image to an intermediate file. |
Contributor |
John McTainsh
|
Published |
30-Jul-2001 |
Last updated |
30-Jul-2001 |
|
|
Introduction
The ASPX page noted below will extract an image from a database and display it on a web
page. At not time will the file be saved to disk. The image in this example is extracted
from a BLOB holding a GIF image. This example uses the Logo table located in the
pubs
database. This database is provided with Microsoft SQL Server 2000 as sample data.
This article is based on MSDN Article ID: Q173308. HOWTO: Display Images Stored in a BLOB Field
Getting started
The following code should be placed in an file called
DisplayImage.ASPX .
<%@ Page LANGUAGE="c#" Debug="true" ContentType="image/gif"%>
<%@ Import namespace="System.Data" %>
<%@ Import namespace="System.Data.SqlClient" %>
<%
// Set the inital type of image (image/jpeg or image/gif) or (text/html)
try
{
// Open database
SqlConnection dbConn = new SqlConnection("data source=localhost;initial catalog=pubs;integrated security=SSPI;");
//SqlConnection dbConn = new SqlConnection("data source=localhost;initial catalog=pubs;UID=sa;PWD=;");
string sImageID = Request.Params["ImageID"];
string sSqlQuery = "SELECT Logo FROM pub_info WHERE pub_id='" + sImageID + "'";
SqlDataAdapter da = new SqlDataAdapter( sSqlQuery,dbConn);
// Load into memory
DataSet ds = new DataSet();
da.Fill( ds );
// Check for data
if( ds.Tables[0].Rows.Count > 0 )
{
// Output the data to the
Response.BinaryWrite( ds.Tables[0].Rows[0][0] as byte [] );
}
else
{
// No Database match found
Response.ContentType = "text/html";
Response.Write("<b>Image not found!</b><br>");
Response.Write("Expected format http://..../DisplayImage.aspx?ImageID=0877<br>");
Response.Write("Recieved ImageID =" + sImageID + "<br>");
}
}
catch( Exception ex )
{
Response.ContentType = "text/html";
Response.Write("<b>Read failed due to excepetion!</b><br>");
Response.Write(ex.ToString());
}
Response.End();
%>
Recalling the image on its own page
The images can be extracted in one of two ways. The first is to call the page
directly from the Internet Explorer Address bar. The line for this should
read as follows;
http://..../DisplayImage.aspx?ImageID=0877
This will display image with an ID of 0877. Using this methods is handy
when you are testing to code and need to display the messages that
indicate error conditions.
Inserting the image into a web page
This second method displays the image on the web page an a normal image would
appear. The following HTML is inserted directly into the page to display the image.
<IMG SRC="DisplayImage.ASPX?ImageID=9999">
Note here the image to be display is the one with ID of 9999.
|