5,422,921 members and growing! (17,109 online)
Email Password   helpLost your password?
Web Development » Charts, Graphs and Images » Images and multimedia     Intermediate

How to read BLOBs and display them

By Kelum W. Ganegoda

Reading BLOBs (images) from a database and displaying them in an ASP.NET application.
C#, Windows, .NET, Visual Studio, ASP.NET, ADO.NET, Dev

Posted: 24 Mar 2006
Updated: 24 Mar 2006
Views: 32,073
Bookmarked: 37 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
15 votes for this Article.
Popularity: 3.38 Rating: 2.88 out of 5
3 votes, 20.0%
1
2 votes, 13.3%
2
2 votes, 13.3%
3
5 votes, 33.3%
4
3 votes, 20.0%
5

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.

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

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

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

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.

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

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

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

About the Author

Kelum W. Ganegoda


I am MCSD for .NET since 2004. I was freelance developer since 2002 to 2005. Projects was done by Ms-VB 6.0 and C#.Net. Now I'm join to the Stellar Vision Technologies as a programmer analyst. .Net is my core. (Thanks Microsoft.). I'm working using .NET since it's first release. I've been assign as Associate Indivitual Role in Microsoft partner program.
Occupation: Web Developer
Location: Sri Lanka Sri Lanka

Other popular Charts, Graphs and Images articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 8 of 8 (Total in Forum: 8) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralMultiple TiffsmemberSundip Nair0:34 17 Jan '07  
AnswerRe: Multiple TiffsmemberKelum W. Ganegoda21:22 24 Jan '07  
GeneralRe: Multiple TiffsmemberSundip Nair21:50 24 Jan '07  
AnswerRe: Multiple TiffsmemberKelum W. Ganegoda2:22 26 Jan '07  
GeneralWhy use a aspx when the ashx is designed to handle such requests ?memberVeritax7:22 7 May '06  
General.Tiff imagesmemberRSBCTrumpet1:16 28 Mar '06  
AnswerRe: .Tiff imagesmemberKelum Ganegoda10:29 30 Mar '06  
GeneralA related topicmemberDylan Thomas12:20 27 Mar '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 24 Mar 2006
Editor: Smitha Vijayan
Copyright 2006 by Kelum W. Ganegoda
Everything else Copyright © CodeProject, 1999-2008
Web15 | Advertise on the Code Project