AJM
AJM

Reputation: 32490

Serving an Image stored in a database on an aspx page

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?

Upvotes: 3

Views: 368

Answers (4)

Sameer Joshi
Sameer Joshi

Reputation: 87

Retrieve it from the database, convert from binary to image using The System.Drawing.Image class, and then save the image in a temporary folder. Give the path of temp folder in <img> 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:

<img src="Temp/xyz.jpg">

Upvotes: 1

Daniel Dyson
Daniel Dyson

Reputation: 13230

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();
                    }
                }
            }
        }

Upvotes: 3

Hans Kesting
Hans Kesting

Reputation: 39274

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.

Upvotes: 2

Andrey
Andrey

Reputation: 60065

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

Plus i recommned storing images on filesystem, not DB.

Upvotes: 2

Related Questions