65.9K
CodeProject is changing. Read more.
Home

ShowImages: a usercontrol to display your web images

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.63/5 (5 votes)

Oct 19, 2004

CPOL

1 min read

viewsIcon

78979

downloadIcon

1723

ShowImages is a simple usercontrol built to facilitate the display of your images/photos stored on web server.

Sample Image - ShowImages.jpg

Introduction

ShowImages is a simple user control built to facilitate the display of your images/photos stored on a web server.

Using the code

ShowImages is a simple user control built to facilitate image display. To see how this user control really works, please visit my site.

ShowImages shows thumbnails, generated by the page getThumbnail.aspx (included in the project), using a DataList. Using ShowImages properties, it is possible set up the Item DataList, and width and height of thumbnails.

Properties of ShowImages are displayed in the following code:

    // font properties
    // specify font family names (comma separated)
    // i.e.: verdana,serif
    // Arial Narrow,verdana
    public string FontName
    {
        set
        {
            fontName = value;
        }
    }

    // specify font size property
    // ie: 10px
    // xx-small
    public string FontSize
    {
        set
        {
            fontSize = value;
        }
    }

    public Boolean FontBold
    {
        set
        {
            fontBold = value;
        }
    }

    // thumbnails
    // height and width
    public int ThumbsHeight
    {
        set 
        {
            thumbnailHeight = value;
        }
    }

    public int ThumbsWidth
    {
        set 
        {
            thumbnailWidth = value;
        }
    }

    // decide how many columns must
    // have the image datalist
    public int Columns
    {
        set
        {
            columns = value;
        }
    }

    // set directory where to find images
    public string DefaultDir
    {
        set
        {
            imagespath = value;
        }
    }


    // set search pattern
    // multiple pattern must be separated by ";"
    // i.e.: *.jpg;*.gif
    public string SearchPattern
    {
        set
        {
            string [] split = null;

            split = value.Split(';');

            foreach (string s in split)
            {
                searchPatternList.Add(s);
            }
        }
    }

ShowImages uses the DefaultDir property to start to navigate inside your image directories. It shows images filtered by the SearchPattern property; if sub-directories are present, ShowImages shows folder entries so you can navigate them.

The following function fills the DataList with images' data.

    /// <SUMMARY>
    /// BuildImagesList
    /// create the image list and
    /// fill the datalist
    /// <PARAM />
    /// </SUMMARY>
    private void BuildImagesList()
    {
        // Create new DataTable objects.
        DataTable myDataTable = new DataTable();
        // Declare DataColumn and DataRow variables.
        DataColumn myColumn;
        DataRow myRow; 

        // Create new DataColumn, set DataType,
        // ColumnName and add to DataTable.    
        myColumn = new DataColumn();
        myColumn.DataType = System.Type.GetType("System.String");
        myColumn.ColumnName = "filename";
        myDataTable.Columns.Add(myColumn);

        // Create second column.
        myColumn = new DataColumn();
        myColumn.DataType = Type.GetType("System.Int32");
        myColumn.ColumnName = "type";
        myDataTable.Columns.Add(myColumn);


        physicalpath = Server.MapPath(imagespath);

        string[] dirList;
        try
        {
            dirList = Directory.GetDirectories(physicalpath);

            // it's a subdir of default dir
            // so I add a link to parent folder
            if (! isMainDir)
            {
                myRow = myDataTable.NewRow();
                myRow["filename"] = getParentDirName(imagespath);
                myRow["type"] = 0; 
                myDataTable.Rows.Add(myRow);
            }

            foreach (string s in Directory.GetDirectories(physicalpath))
            {
                myRow = myDataTable.NewRow();
                myRow["filename"] = addFolderToString(imagespath, 
                                            Path.GetFileName(s));
                myRow["type"] = 1; // directory
                myDataTable.Rows.Add(myRow);

            }

            for (int i=0; i < searchPatternList.Count; i++)
            {
                foreach (string s in Directory.GetFiles(physicalpath, 
                         searchPatternList[i].ToString()))
                {
                    myRow = myDataTable.NewRow();
                    myRow["filename"] = addFolderToString(imagespath, 
                                                Path.GetFileName(s));
                    myRow["type"] = 2; // file
                    myDataTable.Rows.Add(myRow);

                }
            }
            DataView sortedView = new DataView(myDataTable);
            sortedView.Sort = "type, filename asc";

            dlImages.RepeatColumns = columns;
            dlImages.DataSource = sortedView; 
            dlImages.DataBind();

            sortedView = null;
            myDataTable = null;
        }
        catch (Exception ex)
        {}
        finally
        {}

    }

User control DataList has the following item template:

    ...
    <ItemTemplate>
        <br>
        <a
        href="" runat= "server" id= "imgLink"><img runat="server" border="0" 
                id="imgThumbnail" align="middle">
        </a>
        <br>
        <asp:Label Runat="server" ID="imgName" Font-Bold="True" ></asp:Label>
    </ItemTemplate>
    ...

Which is filled with correct data using the ItemDataBound event:

    /// <SUMMARY>
    /// map ItemDataBound events to format
    /// correctly items
    /// </SUMMARY>
    /// <RETURNS></RETURNS>
    private void dlImages_ItemDataBound(Object sender, 
            System.Web.UI.WebControls.DataListItemEventArgs e)
    {
        System.Web.UI.HtmlControls.HtmlImage img = null;
        System.Web.UI.HtmlControls.HtmlAnchor imgLink = null;
        System.Web.UI.WebControls.Label imgName = null;

        //make sure this is an item in the data list (not header, ecc.)
        if ( (e.Item.ItemType == ListItemType.Item) ||
            (e.Item.ItemType == ListItemType.AlternatingItem) )
        {
            // get a reference to the image, link and label
            img = (System.Web.UI.HtmlControls.HtmlImage)
                  (e.Item.FindControl("imgThumbnail"));
            imgLink = (System.Web.UI.HtmlControls.HtmlAnchor)
                      (e.Item.FindControl("imgLink"));
            imgName = (System.Web.UI.WebControls.Label)
                      (e.Item.FindControl("imgName"));

            // if necessary set label font
            imgName.Font.Bold = fontBold;
            if ( fontName.Length > 0)
            {
                imgName.Font.Names = fontName.Split(',');
            }
            if (fontSize.Length > 0)
            {
                FontUnit fu = new FontUnit(fontSize);
                imgName.Font.Size = fu;
            }

            if ((((System.Data.DataRowView)
                  (e.Item.DataItem))[1]).ToString() == "0")
            {
                // format parent directory item
                imgLink.HRef = Request.Url.AbsolutePath + "?path=" + 
                  (((System.Data.DataRowView)(e.Item.DataItem))[0]).ToString();
                img.Src = "cartella.bmp";
                imgName.Width = thumbnailWidth;
                imgName.Text = "..";
                img.Alt = "Come back to parent folder";
            }
            else if ((((System.Data.DataRowView)
                       (e.Item.DataItem))[1]).ToString() == "1")
            {
                // format directory items
                imgLink.HRef =  Request.Url.AbsolutePath  + "?path=" + 
                  (((System.Data.DataRowView)(e.Item.DataItem))[0]).ToString();
                img.Src = "cartella.bmp";
                imgName.Text = getFileName((((System.Data.DataRowView)
                                           (e.Item.DataItem))[0]).ToString());
                img.Alt = "Click to explore dir\n" + imgName.Text;
            }
            else
            {
                // format file items
                imgLink.HRef = 
                  (((System.Data.DataRowView)(e.Item.DataItem))[0]).ToString();
                imgLink.Target = "_balnk";
                img.Src = "getThumbnail.aspx?img=" + 
                    (((System.Data.DataRowView)(e.Item.DataItem))[0]).ToString() + 
                    ((thumbnailHeight>0)?"&height="+ 
                      thumbnailHeight.ToString():"") + 
                    ((thumbnailWidth>0)?"&width="+ 
                      thumbnailWidth.ToString():"");
                imgName.Text = getFileName((((System.Data.DataRowView)
                                           (e.Item.DataItem))[0]).ToString());
                img.Alt = "Click to zoom\n" + imgName.Text;
            }
        }
    }

Using the user control is very easy. You have to insert a Register directive, and a code like the following, in your aspx page.

    ...
    <uc1:ShowImages id="ShowImages1" runat="server" 
        ThumbsHeight="100" ThumbsWidth="170" FontBold="false"
        FontSize="xx-small" FontName="verdana" 
        SearchPattern="*.jpg;*.gif" DefaultDir="/webimages">
    </uc1:showimages>
    ...

Note

Source code includes a Visual Studio Solution named "webalbum". Unzip it in your hard disk and create a web site, on port 8081, pointing to webalbum directory. That's all.