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 3

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

GridView with Thumbnail Images – Part 3

GridView with thumbnail Images, Part 1 and Part 2 of this article series discussed how to generate thumbnail images from the Images stored in database. I will continue this article series with Part 3, which is aimed to generate thumbnail images from the images stored in a file system instead of database. In previous parts, we have stored the images in a database BLOB filed which is then converted to a thumbnail image for displaying in the GridView to have a consistent look. This article will store the image in the file system and the image location in the database, which is then converted to a thumbnail image when displayed in Gridview for having a consistent look.

 

We will create the thumbnail image using HttpHandler like we did in Part 1and Part 2.

 

Creating Thumbnail Image

Thumbnail.ashx

public void ProcessRequest (HttpContext context) {

        string imageurl = context.Request.QueryString["ImURL"];

        string str = context.Server.MapPath(".") + imageurl;

        Bitmap bmp = new Bitmap(str);

System.Drawing.Image img = bmp.GetThumbnailImage(100, 100, null, IntPtr.Zero);

        MemoryStream ms = new MemoryStream();

        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

        byte[] bmpBytes = ms.GetBuffer();

        img.Dispose();

        ms.Close();

 

        context.Response.BinaryWrite(bmpBytes);

        context.Response.End();          

       

    }

Note:

I have given only the ProcessRequest() method in the above code. Refer the source code attachment for the full code.

 

In the above code, we are reading a BitMap image object by reading the image from the file system. BitMap object has method called GetThumbnailImage which accepts height and width to create thumbnail image from the existing image. The created thumbnail image is then converted to byte array(bmpBytes) using MemoryStream object and it is outputted by doing a binary write.

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. 

 

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

 

Now, the created thumbnail image should be displayed in a GridView column. When the user clicks this thumbnail image on the gridview, it should open a popup window and display the full image. This can be done by passing the image link as a querystring to an aspx page which has an Image control. Next section will help us achieving the same.

 

Displaying the Original Image in a Popup Window

We will create page which accepts the image link as a Querystring and assign it ImageUrl property of the image control.

Refer the code below,

FullImage.aspx

    protected void Page_Load(object sender, EventArgs e)

    {       

        string imageurl = Request.QueryString["ImURL"];

        string str = Server.MapPath(".") + imageurl;

        Image1.ImageUrl = str;

    }

 

Binding the GridView

We have the thumbnail HttpHandler and the full image generating aspx page 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.aspx?ImURL=<%#Eval("Image")%>','_blank','toolbar=no,menubar=no'))"> <asp:Image ID="Image1" runat="server" ImageUrl='<%# "ThumbNailImage.ashx?ImURL="+Eval("Image")  %>'/> </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.

 

The main drawback of the above approach is, we are opening the full image in a popup window and we all know that displaying something on a popup window will not give a better user experience. There might be a chance where the popup blocker is turned on in the user’s machine and will not allow the user to view the full image. The next section will mitigate the above drawback by displaying the full image in a DIV tag instead of a popup window.

 




Using DIV Tag to display the full image

We will declare a DIV tag in the ASPX page with display property set to none. This indicates that the DIV tag will not visible by default when the page is loaded. Declare a <IMG> tag inside this DIV tag to display the full image. When the user clicks the thumbnail image, we can enable the DIV tag through a javascript function and pass the ImURL of the image for displaying the full image in the <img> tag. We will also have a button called Close inside the DIV tag to close the display of full image i.e. on click of this button we will again make the DIV tag’s display property to none. Refer the below Jscript code,

 

<script language="javascript">

function ShowDIV(ImURL)

{

        var obj = document.getElementById("IMGDIV");

        var im = document.getElementById("imIMG");

        if ( obj != null )

        {

            obj.style.display = "block";

            im.src = "/GridviewThumbNailImageFS"+ImURL;

        }      

}

function HideDIV()

{   

       var obj = document.getElementById("IMGDIV");

        if ( obj != null )

        {

          obj.style.display = "none";

        }     

}

</script>

ASPX

 <form id="form1" runat="server">

    <div>

<asp:GridView Width="500px" 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(ShowDIV('<%# Eval("Image")%>'));" > <asp:Image ID="Image1" runat="server" ImageUrl='<%# "ThumbNailImage.ashx?ImURL="+ Eval("Image")  %>'/> </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>   

    </div>

    <div id="IMGDIV" align="center" valign="middle" runat="server" style="position: absolute;left: 35%;top: 25%;display:none;visibility:visible;vertical-align:middle;border-style:inset;border-color:black;background-color:#c8d1d4;">

    <table><tr><td><img id="imIMG" /></td></tr><tr><td> <input type="button" style="vertical-align:text-top" value="Close" onclick="return HideDIV();" /></td></tr></table>

   </div>

</form>

 

Codebehind

protected void Page_Load(object sender, EventArgs e)

{

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

        SqlCommand command = new SqlCommand("SELECT imagename,ImageID,Image from [ImageFS]", connection);

        SqlDataAdapter ada = new SqlDataAdapter(command);      

        ada.Fill(dt);

        gvImages.DataSource = dt;

        gvImages.DataBind();

}

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

On clicking the thumbnail, we can view the full image inside a DIV tag like below,

 

 Clicking Close button will close the image in other words closes the DIV tag.

 

Note:

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

 

Downloads

Source

 

Reference

GridView with Thumbnail Images – Part 1

GridView with Thumbnail Images – Part 2

HttpHandler in ASP.Net: PART 1

HttpHandler in ASP.Net: PART 2

 

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