Advertisement:

Skystone Software

http://www.SkystoneSoftware.com

Scott Waletzko's Blog
Enumerating ImageFormats
Published: 9/24/2007
XMl / RSS

Recently I wrote an article about accessing the ImageFormat class properties by name, a complication because ImageFormat is not an enumeration (although it should appear to be one). There are times when it would certainly be useful to enumerate these values (if you want to display a list of image types to your user, for example). Doing so also requires the use of Reflection, here's an example:

VB:
Private Function GetImageFormatNames() As List(Of String)
    Dim clsRet As New List(Of String)
    Dim clsType As Type = GetType(System.Drawing.Imaging.ImageFormat)
    Dim uFlags As System.Reflection.BindingFlags = _
		Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Static
    For Each clsProperty As System.Reflection.PropertyInfo In clsType.GetProperties(uFlags)
        If (clsProperty.Name <> "Guid") And (clsProperty.Name <> "MemoryBmp") Then
            clsRet.Add(clsProperty.Name)
        End If
    Next
    Return clsRet
End Function	
	
C#:
private List<string>GetImageFormatNames()
{
	List<string> clsRet = new List<string>();	
	Type clsType = typeof(System.Drawing.Imaging.ImageFormat);	
	System.Reflection.BindingFlags uFlags = 
		Reflection.BindingFlags.Public | Reflection.BindingFlags.Instance | Reflection.BindingFlags.Static;		
	foreach (System.Reflection.PropertyInfo clsProperty in clsType.GetProperties(uFlags))
	{
		if ((clsProperty.Name != "Guid") & (clsProperty.Name != "MemoryBmp"))
			clsRet.Add(clsProperty.Name);
	}
	return clsRet;
}	
	

Here's how you'd use this to populate a ListBox of image type names:

VB:
For Each sName As String In GetImageFormatNames()
    Me.ListBox1.Items.Add(sName)
Next
	
C#:
foreach (string sName in GetImageFormatNames())
{
	this.ListBox1.Items.Add(sName);
}
	



Questions or Comments? .

VB to C# and C# to VB translation provided by Instant C# and Instant VB.