Retrieving Images from a Database

The Rest is a Piece of Cake

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().

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“PHP is a minor evil perpetrated and created by incompetent amateurs, whereas Perl is a great and insidious evil perpetrated by skilled but perverted professionals.” - Jon Ribbens