The Rest is a Piece of Cake
if ( dr.Read()) //yup we found our image
{
Response.ContentType = dr["img_contenttype"].ToString();
Response.BinaryWrite( (byte[]) dr["img_data"] );
}
connection.Close();
We check to see if any records were returned, by if (dr.Read() )
.
We tell the browser what content type it will be receiving from dr["img_contenttype"].ToString()
and
we output the binary image data by performing a Response.BinaryWrite
,
and casting our binary data to a byte array: Response.BinaryWrite( (byte[])
dr["img_data"] );
.
Lets Test
So how do we link to our new image source. We put the path of our .aspx page as the "src" attribute of the image. Here is a sample html file that demonstrates this.
<html>
<head><title>View Image from the database</title></head>
<body bgcolor=#FFFFFF>
Here is the image, viewed from a database:<br />
<img src="viewimage.aspx?img=1" border=1>
</body>
</html>
Conclusion
Retrieving binary data out of a database isn't really that difficult. We
connect to our database, retrieve the content-type, and output the binary
data using
Response.BinaryWrite()
.
Comments