Here is one way to do it. First add Image control to the view:
<asp:Image runat="server" ImageUrl='<%# Eval("PictureID", "pic.ashx?id={0}") %>' />
Take notice image's url: pic.ashx?id=<picture id>
When browser sees this, it calls back the server to download the image. Then write custom HTTP handler to spout out the image:
Code:
public class PictureLoader : IHttpHandler
{
bool IHttpHandler.IsReusable { return false; }
void IHttpHandler.ProcessRequest(HttpContext context)
{
SqlConnection conn = ...
SqlCommand cmd =
new SqlCommand("SELECT PictureData FROM Pictures WHERE PictureID = @id", conn);
byte[] pictureData = (byte[])cmd.ExecuteScalar();
context.Response.StatusCode = 200;
context.Response.AddHeader("Content-Length", pictureData.Length.ToString());
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(pictureData);
context.Response.End();
}
}
Then register your handler in web.config like this:
Code:
<system.web>
<httpHandlers>
<add path="pic.ashx" verb="GET" type="PictureLoader" />
</httpHandlers>
...
And because I'm lazy writer remember to check from MSDN what all those custom handlers are/do and you get a clearer picture about all of this.