ASP.NET store Image in SQL and retrieve for Asp:Image

Solution 1:

As Joel mentioned you should use an HttpHandler or a page to display the image. Here is a sample code to output image (Image.ashx) :

// ProcessRequest method of Image.ashx
long imageId = Convert.ToInt64(Request.QueryString["ImageId"]);

using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand(
    "SELECT ImageFile FROM ImageTable WHERE ImageId = @ImageID", conn))
{
    command.Parameters.Add("@ImageID", SqlDbType.Int).Value = imageId;
    conn.Open();

    Response.ContentType = "image/gif";
    Response.BinaryWrite((byte[]) command.ExecuteScalar());
}

and then use image in your page as :

  <asp:Image id="Image1" runat="server" ImageUrl="Image.ashx?ImageID=12"/>

Solution 2:

The important thing to remember here is that you shouldn't try to transmit the image data with the profile page itself. Instead, you want your profile page to generate HTML markup for the browser that looks something like this:

<img src="~/MyImageHandler.ashx?UserID=1234" alt="User 1234 avatar" width="100px" height="150px" />

That is the ultimate result of your <asp:Image .../> control. Then the browser will send a completely separate Http request to retrieve the image. That's how pictures on web sites work. You then need to be able to handle that additional request. To do that, create an Http handler (*.ashx file) and use it to retrieve the appropriate image data from the database and send it to the browser.

Solution 3:

If you're using SQL 2005 or greater you should not use the data type Image because it's now deprecated. Instead you want to use the new Varbinary(MAX) type if possible. Once you have it stored all you need to do is retrieve it via ADO.Net call and cast the cell value into type Byte[] and then call Response.BinaryWrite like in ScarletGarden's example above.