Use Javascript and an HttpHandler to Load an Image from a Database

This might be part of another ongoing series, but the for this post, right here, RIGHT NOW, I am going to show are really simple but fun (??) way to change an image’s… eh image from a database stored image using Javascript and an .ashx file. And when I say simple, I mean it took me longer to get test code going than it did to make this work.

First you need a handler (If you don’t what this is for, well for this example it allows you to create a non existant url for an image loaded from the database.) which is aptly named Generic Handler when you do the usual Add New Item. Amazing. You should get something like this in the class file:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class SomeImage: IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
        }

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

Yeah you like that don’t you? Yeah you do.

So now we have something to display the image right? Well that’s pretty easy too. For me, I have an UserImage class I created with Linq to Sql to mimic my UserImage table. I’m cool like that. I then created a method to return the image bytes based on the ID sent in. That part is up to you how to handle. The main thing you need is to get the image bytes somehow. With that in mind, here is what the class file looks like now:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ShowImage : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            Int32 imageID;
            Byte[] imageBytes;

            imageID = Convert.ToInt32(context.Request.QueryString["ImageID"]);
            imageBytes = UserImage.GetImageBytesById(imageID);
            context.Response.ContentType = "image/jpeg";
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.BufferOutput = false;
            context.Response.OutputStream.Write(imageBytes, 0, imageBytes.Length);
        }

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

As you can see, the query string has an id being sent in and I’m retrieving it. From there I get the image bytes, tell the context what it is, how to handle the cache, and sending the bytes out. What you can’t see right now is that somewhere I have something that looks like this:

   <image src="SomeImage.ashx?ImageID=1" />

When that url is read, it will send it off to the handler to get and display the image. (Not taking caching into account mnd you)

Now I know what you’re thinking right now, “I’m bored” which I understand but you’re also thinking, “Where’s the f@&#ing javascript?”. Well my vulgar friend, it’s on the way.

<head runat="server" >
        <script type="text/javascript" language="javascript">
        function TestThis(name, imageID)
        {
            var test = document.getElementById(name);
            test.src = 'ShowImage.ashx?imageID=' + imageID;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div style="background-color:Gray;height:20px;width:20px;" onclick="TestThis('hi', 1);"> </div>
        <div style="background-color:Red;height:20px;width:20px;" onclick="TestThis('hi', 2);" > </div>
        <div style="background-color:Blue;height:20px;width:20px;" onclick="TestThis('hi', 3);"> </div>
        <br />
        <img src="" id="hi" name="hi" />
    </div>
    </form>
</body>

So now every time one of the three divs is “clicked”, the image is changed depending on the image id sent in using the “url” of the handler you created. Much like sending information to another page, you send the id to the handler so it can display the correct image.

I realize this isn’t the best of examples but it’s a push in the right direction. Maybe next time you want something, you won’t swear at me.

One thought on “Use Javascript and an HttpHandler to Load an Image from a Database”

Comments are closed.