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

ShowImages: a usercontrol to display your web images

Rate me:
Please Sign up or sign in to vote.
3.63/5 (5 votes)
19 Oct 2004CPOL1 min read 78.4K   1.7K   33   10
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:

C#
// 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.

C#
/// <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:

ASP.NET
...
<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:

C#
/// <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.

ASP.NET
...
<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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRegister TAG Pin
Leonardo.Nakahara3-Mar-08 8:31
Leonardo.Nakahara3-Mar-08 8:31 
QuestionHow to show an image title Pin
bruh_man18-Mar-05 9:01
bruh_man18-Mar-05 9:01 
AnswerRe: How to show an image title Pin
mbeatini21-Mar-05 6:04
sussmbeatini21-Mar-05 6:04 
GeneralRe: How to show an image title Pin
bruh_man21-Mar-05 9:39
bruh_man21-Mar-05 9:39 
GeneralRe: How to show an image title Pin
mbeatini23-Mar-05 6:00
sussmbeatini23-Mar-05 6:00 
Ok,
this is not the aim of the showimages usercontrol but using a trick we can do it!

To classify your images you have to use file extra information such author, title, comments...
I modified my code to retrieve image category from "comments" information associated to files.
About the "bikes.gif":
1. using the right mouse button open the properties tab and insert into the "comments" field the value "bikes"
2. insert this code in your web.config file:
<appSettings><br />
    <!-- <br />
add a key for each category <br />
and use value to set the web page<br />
--><br />
    <add key="bikes" value="bikes.aspx" /><br />
</appSettings><br />

3. substitute the BuildImagesList code with the following
<code>
/// <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);

			// Create new DataColumn, set DataType, ColumnName and add to DataTable.    
	myColumn = new DataColumn();
	myColumn.DataType = System.Type.GetType("System.String");
	myColumn.ColumnName = "category";
	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; 
			myRow["category"] = "";
			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
			myRow["category"] = "";
			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
				
						try
				{

					// Creating a ShellClass Object from the Shell32
					Shell32.ShellClass sh = new Shell32.ShellClass();
					// Creating a Folder Object from Folder that inculdes the File
					Shell32.Folder dir = sh.NameSpace( Path.GetDirectoryName( s ) );
					// Creating a new FolderItem from Folder that includes the File
					Shell32.FolderItem item = dir.ParseName( Path.GetFileName( s ) );
					
					int itemindex = 14;
						// read the current detail Info from the FolderItem Object
						//(Retrieves details about an item in a folder. For example, its size, type, or the time of its last modification.)
						// some examples:
						// 14 Comments of the item. 

					string det = dir.GetDetailsOf( item, itemindex );
					myRow["category"] = det;

				}
				catch(Exception)
				{
					myRow["category"] = "";
				}

				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
	{}

}
</code>

4. modify the dlImages_ItemDataBound event in ShowImages.ascx.cs file as shown below
....
else
{
	// format file items
	string key = (((System.Data.DataRowView)(e.Item.DataItem))[2]).ToString();
	string keyval;
	// there is a category? 
	// yes, try to retrieve the webpages from appsettings
	// no or there's an error use file name 

	try 
	{
		if (key.Length > 0)
		{
			keyval = System.Configuration.ConfigurationSettings.AppSettings[key].ToString();
		}
		else
		{
			keyval = (((System.Data.DataRowView)(e.Item.DataItem))[0]).ToString();
		}
	}
	catch
	{
		keyval = (((System.Data.DataRowView)(e.Item.DataItem))[0]).ToString();
	}

	imgLink.HRef = keyval;
	imgLink.Target = "_blank";
	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());
	imgName.Text = imgName.Text.Substring(0, imgName.Text.IndexOf("."));
	img.Alt = "Click to zoom\n" + imgName.Text;
}
....


That's all.
Let me Know!
Bye, Smile | :)

Massimo
GeneralRe: How to show an image title Pin
mbeatini23-Mar-05 7:16
sussmbeatini23-Mar-05 7:16 
GeneralRe: How to show an image title Pin
bruh_man23-Mar-05 8:30
bruh_man23-Mar-05 8:30 
GeneralRe: How to show an image title Pin
mbeatini29-Mar-05 20:51
sussmbeatini29-Mar-05 20:51 
GeneralPort 8081 Pin
TBermudez19-Oct-04 8:47
TBermudez19-Oct-04 8:47 
GeneralRe: Port 8081 Pin
19-Oct-04 20:39
suss19-Oct-04 20:39 

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.