13

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?

2

6 Answers 6

18

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).

Sign up to request clarification or add additional context in comments.

3 Comments

I know this is old, but I think you have what I'm looking for here. I'm just missing the knowledge right now, to figure it out. I've got my handler written. Here it is pastebin.com/m75e17237 and I've got the call to that handler. It looks like this: pastebin.com/m63e1ebc3 But when the page loads, I just get the missing image little red X box. I've never used a handler before, so may be doing something wrong. One thing I notice is that if I set a breakpoint in the handler, it never gets there. Any advice would be awesome, if you get a chance. -Will
@aape: did you register the handler in web.config?
Trying to get an answer to my issue here, I have two images which I want to display on a view depending on whether a student is enrolled or not, This view I have is strongly typed, how can I get this to work?
9

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.

1 Comment

What is image/pjpeg? It's a bug in IE, not a valid mime-type to be used on the server ;)
5

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

3 Comments

Wow! This question is more than a year old! Thanks for the answer, however I have resolved the issue! +1 for the well documented answer.
Alternatively, you can cache to disk and allow IIS to handle ETag, Last-Modified, etc. Like ImageResizing.net does. IIS does have a good performance advantage over managed code for serving static files, even with an optimal .NET implementation.
Thats why I do my processing offline and in a scalable way. github.com/taliesins/talifun-commander
2

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.

Comments

0

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.

2 Comments

link doesn't work
Unfortunately CodePlex shut down years ago, and the sample for this is long gone now. A solution is available in the check-marked answer on this page.
0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.