Home > View Post

Part V. Viewing the Binary Image stored in the Database

Previously, we introduced a series of posts that would show the interesting parts of a (very basic) feedback service implementation. This is part V, here are the other bits:

Viewing the Binary Image stored in the Database

In Part II we successfully managed to store our image in a varbinary column in our database.

This time we're going to start building our very simple ASP.NET application that will allow us to view the feedback data we've collected. Today we're going to focus on viewing those screenshots.

Much of what we cover today has been covered by David Hayden in his great post called Saving and Displaying Photos in SQL Server using ASP.NET with a few subtle changes.

1. We're going to use an .ashx (handler) not a .aspx (page).

Handlers are more lightweight than pages so if you don't need a page, don't use it. I have a simple rule to help you make that decision: If you're not using server controls use a handler..

No sign of any ASP.NET controls here so a handler it is, and we're going to call it ViewPng.ashx.

2. We're not going to bother with the Image type, we're just going to write the byte[] data directly to the stream.

public class ViewPng : IHttpHandler
    public void ProcessRequest (HttpContext context)
        // get the id of the feedback data from the querystring
        int id = int.Parse(context.Request.QueryString["id"]);

        // pull the data from the Dal
        byte[] data = FeedbackDal.GetScreenGrabById(id);

        // set the content type appropriately
        context.Response.ContentType = "image/png";

        // use a binary writer to write the data to the response stream
        using (BinaryWriter bw = new BinaryWriter(context.Response.OutputStream))

    public bool IsReusable
            return false;

Easy peasy. Now we can hit and view any of our images directly in the browser by hitting the appropriate url, e.g.: /ViewPng.ashx?id=123.

Finally, we need to implement our Dal's GetScreenGrabById(int id) method...

public static byte[] GetScreenGrabById(int feedbackId)
    Database db = DatabaseFactory.CreateDatabase("FeedbackService");

    DbCommand cmd = db.GetSqlStringCommand("SELECT ScreenGrab FROM Feedback WHERE FeedbackId = @FeedbackId");

    db.AddInParameter(cmd, "@FeedbackId", DbType.Int32, feedbackId);

    byte[] data = (byte[]) db.ExecuteScalar(cmd);

    return data;

And we're done. We're nearly finished now, but next we'll be looking at creating a report (that links to ViewPng.ashx?id=XX obviously) using .rdlc and the ASP.NET report viewer.

Part VI: Creating the Report

Tags: .NET

Josh Post By Josh Twist
11:38 PM
09 Aug 2007

» Next Post: Generating Xaml on the Server for SilverLight Clients
« Previous Post: Part IV. Sending the Data from the Client

Comments are closed for this post.

© 2005 - 2021 Josh Twist - All Rights Reserved.