Members

Technology Zones

Articles

Hosted By

MaximumASP

Info

Rated
Read 65,906 times

Contents

Related Categories

Retrieving Images from a Database - The Rest is a Piece of Cake

dave123aspx

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

Comments

  • Re: can't get this to work

    Posted by manoj3939 on 18 Apr 2007

    I am Facing the sam e problem, i am able to store an image into a database as image type but fetching from database in displaying it on a web page is not working.


    Fetching from the da...

  • Posted by tomk10 on 14 Dec 2005

    Whar is Bind? I've only seen DataBinder.Eval used here and your examp,le causes a Compilation Error.

  • can't get this to work

    Posted by Jud101 on 25 Nov 2005

    I've been struggling to get an image to view on my webpage. I had to make a few changes but no way would it work for me. I ended up coping and pasting everything, ran into the error at this point : ...

  • Fix

    Posted by Louie88 on 15 Nov 2005

    Hi there! Try this „quite” simple fix. Thanks Dave, you helped a lot with this images mystery…

    ...

  • Same Problem

    Posted by tadhg88 on 22 Feb 2005

    hey guys i have the exact same problem as ye have and im just wondering if ye managed to find a solution
    thanks in advance
    tadhg88