Click here to Skip to main content
15,843,498 members
Articles / Web Development / ASP.NET
Article

How to read BLOBs and display them

Rate me:
Please Sign up or sign in to vote.
2.88/5 (15 votes)
24 Mar 20062 min read 115K   1.4K   50   8
Reading BLOBs (images) from a database and displaying them in an ASP.NET application.

blobreadasp.gif

Introduction

Recently, I developed an E-Commerce site, a mobile phone shopping mall, where pages and its contents are created dynamically when the customer selects his/ her preferred mobile phone. The image of the phone and logo of the phone vendor are stored in the database as BLOB. I wanted to read this BLOB and display it on customer request. I created a sample application, for reading the BLOB and displaying it, to demonstrate this.

I use the pubs database for this example, which is created when SQL Server is installed. I populate the publication IDs from the pub_info table to a dropdown list, and when the selection is done, the appropriate logo will be displayed.

Using the code

Create a separate aspx file to hold the image. An aspx file for holding the image? Are you kidding? Wait, look what is happening. Create a method in the code-behind file of the aspx page to read a BLOB value. CreateImage(string id) is the method that reads the BLOB. The string id parameter gets the image ID that the user selects from the drop down list. To read the BLOB value, use the ExecuteScalar() method of the SqlCommand class. ExecuteScalar() returns an object, so we should cast it and store in a byte array like this.

C#
byte[] _buf = (byte[]) _cmd.ExecuteScalar();

Then, stream it back to the HTTP response. The complete code is shown below:

C#
void  CreateImage(string id)
{
    // Connectoin string is taken from web.config file.
    SqlConnection _con = new SqlConnection(
      System.Configuration.ConfigurationSettings.AppSettings["DB"]);
        
    try
    {
        _con.Open();
        SqlCommand _cmd = _con.CreateCommand();
        _cmd.CommandText = "select logo from" + 
                           " pub_info where pub_id='" + 
                           id + "'";
        byte[] _buf = (byte[])_cmd.ExecuteScalar();
        
        // This is optional
        Response.ContentType = "image/gif";
        
        //stream it back in the HTTP response
        Response.BinaryWrite(_buf);
                
                
    }
    catch
    {}
    finally
    {
        _con.Close();
                
    }
}

In the Page_Load(), call CreateImage().

C#
private void Page_Load(object sender, System.EventArgs e)
{
    if(!IsPostBack)
    {
        CreateImage(Request["id"]);
    }
}

The page retrieves the image ID using a query string. Now, I'm going to display the image. In order to display the image, use a HtmlServerControl where you want. Set its src property like this.

HTML
<img src='<%# "imgs.aspx?id=" + drpIds.SelectedValue %>'>

To evaluate this magical data binding formula, we should call:

C#
Page.DataBind();

in the drop down list's SelectedIndexChanged event.

That's all. Run the application and enjoy it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior) Brandix Lanka Pvt Ltd.
Sri Lanka Sri Lanka
I’ve started my career in 2001 with Microsoft .net ver 1.0. I’m a MCSD for .net.

Currently, I’m working for Sri Lanka’s largest apparel exporter as a Software Engineer. All projects in .net, MS Sql Server, Biztalk Server, WCF and WPF. And also, I’m developing components to the ERP. In addition to that, I’ve involved to create architecture of ERP integration.

Comments and Discussions

 
GeneralMultiple Tiffs Pin
Sundip Nair17-Jan-07 0:34
Sundip Nair17-Jan-07 0:34 
Hi,

Consider a page that is like

<html><br />
  <body><br />
    <INPUT type="button" value="Button"><br />
    <table><br />
      <tr><br />
        <td><br />
        </td><br />
        <td><br />
        </td><br />
      </tr><br />
    </table><br />
    <INPUT type="button" value="Button"><br />
  </body><br />
</html>


Here there are 2 buttons above and below the table. Now I want to display 2 tiff blobs from the DB in the 2 TDs in the above table.

If I try,

bitmap.Save(Context.Response.OutputStream, ImageFormat.Gif)<br />
bitmap.Dispose()


then the contents of the page disapper. The real objective for me is to have a formatted page and Images (n no of images) are filled into respective placeholders.

Sundip

AnswerRe: Multiple Tiffs Pin
Kelum W. Ganegoda24-Jan-07 21:22
Kelum W. Ganegoda24-Jan-07 21:22 
GeneralRe: Multiple Tiffs Pin
Sundip Nair24-Jan-07 21:50
Sundip Nair24-Jan-07 21:50 
AnswerRe: Multiple Tiffs Pin
Kelum W. Ganegoda26-Jan-07 2:22
Kelum W. Ganegoda26-Jan-07 2:22 
QuestionWhy use a aspx when the ashx is designed to handle such requests ? Pin
pirmann7-May-06 7:22
pirmann7-May-06 7:22 
General.Tiff images Pin
User 32700328-Mar-06 1:16
User 32700328-Mar-06 1:16 
AnswerRe: .Tiff images Pin
Kelum W. Ganegoda30-Mar-06 10:29
Kelum W. Ganegoda30-Mar-06 10:29 
GeneralA related topic Pin
Dylan Thomas27-Mar-06 12:20
Dylan Thomas27-Mar-06 12:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.