Dynamically Rendering asp:Image from BLOB entry in ASP.NET

What I want to achieve is this. I want to give the user the ability to upload an image file, store the image in BLOB in SQL Server, and then use this image as a logo in other pages of the site.

I have done this by using

   Response.Clear();
   Response.ContentType = "image/pjpeg";
   Response.BinaryWrite(imageConents);
   Response.End();

but to do this, I use a User control in the place where I want to show the image. I want to do it if possible using an asp:Image control, or even a pure old html image control. Is this possible?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Add a ‘Generic Handler’ to your web project, name it something like Image.ashx. Implement it like this:

public class ImageHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        using(Image image = GetImage(context.Request.QueryString["ID"]))
        {    
            context.Response.ContentType = "image/jpeg";
            image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        }
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}

Now just implement the GetImage method to load the image with the given ID, and you can use

<asp:Image runat="server" ImageUrl="~/Image.ashx?ID=myImageId" />

to display it. You might want to think about implementing some form of caching in the handler too. And remember if you want to change the image format to PNG, you need to use an intermediate MemoryStream (because PNGs require a seekable stream to be saved).

Method 2

You can BASE64 encode the content of the image directly into the SRC attribute, however, I believe only Firefox will parse this back into an image.

What I typically do is a create a very lightweight HTTPHandler to serve the images:

using System;
using System.Web;

namespace Example
{  
    public class GetImage : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.QueryString("id") != null)
            {
                Blob = GetBlobFromDataBase(id);
                context.Response.Clear();
                context.Response.ContentType = "image/pjpeg";
                context.Response.BinaryWrite(Blob);
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

You can reference this directly in your img tag:

<img src="GetImage.ashx?id=111"/>

Or, you could even create a server control that does it for you:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Example.WebControl
{

    [ToolboxData("<{0}:DatabaseImage runat=server></{0}:DatabaseImage>")]
    public class DatabaseImage : Control
    {

        public int DatabaseId
        {
            get
            {
                if (ViewState["DatabaseId" + this.ID] == null)
                    return 0;
                else
                    return ViewState["DataBaseId"];
            }
            set
            {
                ViewState["DatabaseId" + this.ID] = value;
            }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write("<img src='getImage.ashx?id=" + this.DatabaseId + "'/>");
            base.RenderContents(output);
        }
    }
}

This could be used like

<cc:DatabaseImage id="db1" DatabaseId="123" runat="server/>

And of course, you could set the databaseId in the codebehind as needed.

Method 3

You don’t want to be serving blobs from a database without implementing client side caching.

You will need to handle the following headers to support client side caching:

  • ETag
  • Expires
  • Last-Modified
  • If-Match
  • If-None-Match
  • If-Modified-Since
  • If-Unmodified-Since
  • Unless-Modified-Since

For an http handler that does this, check out:
http://code.google.com/p/talifun-web/wiki/StaticFileHandler

It has a nice helper to serve the content. It should be easy to pass in database stream to it. It also does server side caching which should help alleviate some of the pressure on the database.

If you ever decide to serve streaming content from the database, pdfs or large files the handler also supports 206 partial requests.

It also supports gzip and deflate compression.

These file types will benefit from further compression:

  • css, js, htm, html, swf, xml, xslt, txt
  • doc, xls, ppt

There are some file types that will not benefit from further compression:

  • pdf (causes problems with certain versions in IE and it is usually well compressed)
  • png, jpg, jpeg, gif, ico
  • wav, mp3, m4a, aac (wav is often compressed)
  • 3gp, 3g2, asf, avi, dv, flv, mov, mp4, mpg, mpeg, wmv
  • zip, rar, 7z, arj

Method 4

Using ASP.Net with MVC this is pretty forward easy. You code a controller with a method like this:

public FileContentResult Image(int id)
{
    //Get data from database. The Image BLOB is return like byte[]
    SomeLogic ItemsDB= new SomeLogic("[ImageId]=" + id.ToString());
    FileContentResult MyImage = null;
    if (ItemsDB.Count > 0)
    {
        MyImage= new FileContentResult(ItemsDB.Image, "image/jpg");
    }

    return MyImage;
}

In your ASP.NET Web View or in this example, in your ASP.NET Web Form you can fill an Image Control with the URL to your method like this:

            this.imgExample.ImageUrl = "~/Items/Image/" + MyItem.Id.ToString();
            this.imgExample.Height = new Unit(120);
            this.imgExample.Width = new Unit(120);

Voilá. Not HttpModules hassle was needed.

Method 5

We actually just released some classes that help with exactly this kind of thing:

http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16449

Specifically, check out the DatabaseImage sample.

Method 6

Add the code to a handler to return the image bytes with the appropriate mime-type. Then you can just add the url to your handler like it is an image. For example:

<img src="myhandler.ashx?imageid=5">

Make sense?


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x