CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
GridView with Thumbnail Images – Part 1

By Satheesh babu
Posted On Jul 24,2008
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 20
Category: ASP.Net
Print this article.

GridView with Thumbnail Images – Part 1

 

There will be requirements where we need to display the images stored in database in a gridview. Read my previous article on Images in GridView, where I have discussed to bind the images stored in a database BLOB field to a gridview. Images in GridView - this post use an HttpHandler to fetch the image from the database. The main drawback of this approach is, it will stretch the gridview column based on the dimensions of the images stored. Hence, this results in an inconsistent looking gridview after binding it with the images.

It will be good, if the images in the database are rendered as a thumbnail image with a fixed dimension. On clicking the thumbnail image, we can display the whole image stored in the database. This article will help us to accomplish this.

Based on this requirement, I have split this article into 2 parts,

GridView with Thumbnail Images – Part 1 [Current Article]

- Deals with creation of thumbnails and binding it to the GridView. On clicking the gridview the full image will be displayed in a pop up window.

GridView with Thumbnail Images – Part 2

- Deals with creation of thumbnails and binding it to the GridView. On clicking the gridview the full image will be displayed in a DIV tag in the same page.

 

Creating Thumbnail Image

Since the images are stored in a database (BLOB), we need to retrieve the image as a byte array and do a binary write for the images to display in the webpage. To create a Thumbnail of the image, we will retrieve the image from the database as a byte array and create a Thumbnail image by using BitMap and Graphics class. We can do this through an aspx page, but I will use HttpHandler to do this since we do not need some page level events. Read my previous articles on HttpHandler linked in the reference section of this article. 

 

Thumbnail.ashx

public void ProcessRequest (HttpContext context) {

        string imageid = context.Request.QueryString["ImID"];

if (imageid == null || imageid == "")

{

//Set a default imageID

imageid = "1";

}

        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);

        connection.Open();

        SqlCommand command = new SqlCommand("select Image from Image where ImageID="+imageid, connection);

        SqlDataReader dr = command.ExecuteReader();

        dr.Read();

       

        Stream str = new MemoryStream((Byte[])dr[0]);      

 

        Bitmap loBMP = new Bitmap(str);

        Bitmap bmpOut = new Bitmap(100, 100);

 

        Graphics g = Graphics.FromImage(bmpOut);

        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

        g.FillRectangle(Brushes.White, 0, 0, 100, 100);

        g.DrawImage(loBMP, 0, 0, 100, 100);

 

        MemoryStream ms = new MemoryStream();

        bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

        byte[] bmpBytes = ms.GetBuffer();

        bmpOut.Dispose();

        ms.Close();

        context.Response.BinaryWrite(bmpBytes);

        connection.Close();

        context.Response.End();  

       

    }

 

In the above code, we are reading the image as byte array to construct a bitmap object (loBMP). With the help of Graphics class, the thumbnail image is constructed from the original bitmap object which holds the full image. The created thumbnail image is then copied to a bitmap object (bmpOut) and it is outputted by doing a binary write.

 

We can test run this HttpHandler by hard coding an existing imageID in the database.

 

Now, the created thumbnail image should be displayed in a GridView column. When we click this thumbnail image on the gridview, it should open a popup window and display the full image. This can be done by creating another HttpHandler which retrieves the image from the database by taking the ImageID as a QueryString and doing a binary write. Next section will help us doing it.

 

Displaying the Original Image

We will create another HttpHandler which fetches the original image that is stored in the database as a byte array and do a binary write through the response object. Refer the code below,

FullImage.ashx

public void ProcessRequest (HttpContext context) {

       string imageid = context.Request.QueryString["ImID"];

if (imageid == null || imageid == "")

{

//Set a default imageID

imageid = "1";

}

        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);

        connection.Open();

        SqlCommand command = new SqlCommand("select Image from Image where ImageID="+imageid, connection);

        SqlDataReader dr = command.ExecuteReader();

        dr.Read();

        context.Response.BinaryWrite((Byte[])dr[0]);

        connection.Close();

        context.Response.End(); 

    }

 




Note:

I have given only the ProcessRequest() method in the above code. Refer the source code attachment for the full code. I have set default imageID, make sure you are giving an existing imageId in database for the code to work without any errors.

 

Binding the GridView

We have the thumbnail HttpHandler and the full image generating HttpHandler ready which needs to be binded with GridView. Refer the below code,

GridView Code

<asp:GridView ID="gvImages" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" >

      <Columns>

         <asp:BoundField HeaderText = "Image Name" DataField="imagename" />

         <asp:TemplateField HeaderText="Image">

              <ItemTemplate>

                 <a href="javascript:void(window.open('<%# "FullImage.ashx?ImID="+ Eval("ImageID")%>','_blank','toolbar=no,menubar=no'))" > <asp:Image ID="Image1" runat="server" ImageUrl='<%# "ThumbNailImage.ashx?ImID="+ Eval("ImageID")  %>'/> </a>

              </ItemTemplate>

         </asp:TemplateField>              

      </Columns>

   <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />

   <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />

   <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />

   <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />

   <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />

   <AlternatingRowStyle BackColor="White" />

</asp:GridView>

 

When we execute the page we will get an output similar to below.

 

 

Note:

The source code attached with this article has a page for uploading images. Create a table with name Image with columns ImageID(Identity), ImageName(Varchar(50)) and Image(image). Configure the connection string in the web.config file corresponding to the sqlserver you use.

Reference

Images in GridView

ThumbNail Image Creation By Rick

HttpHandler in ASP.Net: PART 1

HttpHandler in ASP.Net: PART 2

 

Download

Download Source

 

Conclusion

When we bind the images of different dimensions stored in database to a gridview it will give an inconsistent look to the gridview. This article will address this issue by creating a thumbnail image for the images and then binding it to a gridview. As we have seen, the full image will be displayed in a popup window. Part 2 of this article deals with the same scenario but the full image display will be displayed within a DIV tag in the same page.

Happy Coding!!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
not working!
context.Response.BinaryWrite((Byte[])dr[0]);
have here problem :|
error in clicking image
i m getting error ,when i clicking image in grid view ..after clicking image,it doesn't shown any image.it showning image icon only.what may be the error in it..could u help me out.please...
Error with deleting image
I loaded image in gridview from data base. when i delete image from gridview it detele form data base. but the image still its display in a gridview. i am using update panel.

how to refersh the image please help me
Great article! Thank you.
Hi, i'm from Brasil and i seeking more for thats solution, thumbnail from the binary data.

Thank you so much.
Edit
Thanks for your article. It made my job a lot easier and better. I was wondering if it possible to add the Edit control
to it so I could replace an image that has been already uploaded with a new.

Thaks again.
DAkreyi
dakreyi@yahoo.com
ketan
Thanks Nice Article.

http://dotnet-magic.blogspot.com/
RE:Comments
Ofcourse, if you dont have issues with database size then go for it! It can be implemented as said by Tim.
run it when loading image
Isn’t better to run the script once and generate all the thumbnails for each image and save them in database so next time just retrieve the thumbnail instead of generating it each time for grid display?
vb.net
This code look easy and very helpful but unfortunately i not really understand C#.anyone can help me translate it to vb.net.already tired searching for topic...thank
Re: Little Help
@Juvan, Yeah, you can do that. In Thumbnail.ashx, for the bitmap object, adjust the initialization value, Bitmap bmpOut = new Bitmap(X, X); In the same way, replace in FillRectangle and DrawImage too, g.FillRectangle(Brushes.White, 0, 0, X, X); g.DrawImage(loBMP, 0, 0, X, X);
Re: Little Help
Hi Satheesh, Thanks for your help. Now every thing looks great. I was wondering if there is a way to reduce the size of thumbnail images? Thanks again
RE: Little Help
@Juvan, I guess, when you are calling the Thumbnail.ashx the imageid is going as null. Please make sure you are not passing nulls as a query string.
Nice, but..
Nice article. Those HttpHandles are really nice to use. But,...with each thumbnail you will retrieve the full image stream from the DB. It would be better to create the thumbnails after an upload of the image.
Thanks
Thanks satheesh. The application is running fine, but when debugging ThumbNailImage.ashx It says: Incorrect syntax near '='. Line 24: SqlDataReader dr = command.ExecuteReader(); SqlDataReader dr = command.ExecuteReader(); Anyway I love it and it is great . I wish if I could have it in DetailsView too. Thanks again
RE: Little Help
@Juvan, Please check whether you have configured the database correctly. You have to use your own DB. Refer the section "Note" above Reference.
Little Help
i dowloaded the code. uploading images no problem. When binding sqldatasoure to Gridview and testing it Ican see the images but in the browser it does not contain images. From debuging it shows the following: Incorrect syntax near '='. SqlDataReader dr = command.ExecuteReader(); Help Is appreciated. heval6@yahoo.com
Nice article
This is such a nice article. It helps me a lot. thank you very much
Great article
Problem uploading image. "Object reference not set to an instance of an object."
Nice
Nice article.
Mr
Great article, thanks a lot. I downloaded the code to test it!