views:

39

answers:

4

I'm pulling back an image that is stored in a column in a SQL server database.

I need to serve this up on an aspx page.

How would I do that?

+2  A: 

You first get Page.Response, then call BinaryWrite or use Stream directly

Plus i recommned storing images on filesystem, not DB.

Andrey
+1  A: 

In the html page, you need to render a <img> tag with a src attribute pointing to another page (or ashx handler). In that other page/handler the only output you generate is the binary data of the image (and possibly some http headers).
Use parameters to specify the image.

Hans Kesting
+2  A: 

I would create an image element where the src attribute points to an ashx handler with the image id in the query string. In this handler, you could have the following code:

        string ImageId = Request.QueryString["img"];
        string sqlText = "SELECT img_data, img_contenttype FROM Images WHERE img_pk = " + ImageId;

        using (var connection = new SqlConnection("your connection string"))
        {
            using (var command = new SqlCommand(sqlText, connection))
            {
                connection.Open();
                using (SqlDataReader dr = command.ExecuteReader())
                {
                    if (dr.Read())
                    {
                        Response.Clear();
                        Response.ContentType = dr["img_contenttype"].ToString();
                        Response.BinaryWrite((byte[]) dr["img_data"]);
                        Response.End();
                    }
                }
            }
        }
Daniel Dyson
+1  A: 

Retrieve it from data base convert from binary to image using system.drawing.image class, then save the image in some temp folder and give the path of temp folder in tag in html/ ascx/aspx etc

C#:

MemoryStream ms = new MemoryStream(binaryImage); Bitmap BMP = new Bitmap(ms); String path = Server.MapPath("..\Temp"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, path); if (SecurityManager.IsGranted(writePermission)) { System.Drawing.Image img = new System.Drawing.Bitmap(ms); img.Save(path + "\xyz.jpg", ImageFormat.Jpeg); }

HTML/ASPX:

Sameer Joshi