Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB7
Expertise: Advanced
Nov 10, 2003

ImageFormatUtils class - Find the ImageFormat for a filename or MIME type

'/// <summary>
'/// Provides static (Shared) methods to find the
'/// ImageFormat for a filename or MIME type.
'/// </summary>
Public NotInheritable Class ImageFormatUtils
    Private Shared codecs() As ImageCodecInfo
    Private Shared formats As Hashtable
    
    Shared Sub New()
        '// Get a combined list of all codecs
        Dim encoders() As ImageCodecInfo = ImageCodecInfo.GetImageEncoders()
        If encoders Is Nothing Then ReDim encoders(0)
        Dim decoders() As ImageCodecInfo = ImageCodecInfo.GetImageDecoders()
        If decoders Is Nothing Then ReDim decoders(0)
        
        Dim codec As ImageCodecInfo
        Dim htCodecs As new Hashtable(encoders.Length + decoders.Length)
        Dim i As Integer
        
        For i = 0 To encoders.Length - 1
            codec = encoders(i)
            htCodecs.Add(codec.Clsid, codec)
        Next
        For i = 0 To decoders.Length - 1
            codec = decoders(i)
            If Not htCodecs.ContainsKey(codec.Clsid) Then
                htCodecs.Add(codec.Clsid, codec)
            End If
        Next
        
        ReDim codecs(htCodecs.Count - 1)
        htCodecs.Values.CopyTo(codecs, 0)
        
        '// Enumerate the pre-defined formats
        Try
            Dim tImageFormat As Type = GetType(ImageFormat)
            Dim props() As PropertyInfo = tImageFormat.GetProperties _
                (BindingFlags.Public Or BindingFlags.Static)
            Dim prop As PropertyInfo
            Dim format As ImageFormat
            
            formats = new Hashtable(props.Length)
            For i = 0 To props.Length - 1
                prop = props(i)
                If prop.PropertyType Is tImageFormat Then
                    format = DirectCast(prop.GetValue(Nothing, Nothing), _
                        ImageFormat)
                    formats.Add(format.Guid, format)
                End If
            Next
        Catch
        End Try
    End Sub
    
    '/// <summary>
    '/// Returns the ImageFormat instance for the
    '/// specified format ID. Uses reflection to
    '/// test the static instances of the class
    '/// for the correct ID, before using the
    '/// constructor.
    '/// </summary>
    '/// <param name="formatID">
    '/// The Guid which contains the format ID.
    '/// </param>
    '/// <returns>
    '/// The corresponding ImageFormat object.
    '/// </returns>
    Public Shared Function FromID(ByVal formatID As Guid) As ImageFormat
        If formats Is Nothing OrElse Not formats.ContainsKey(formatID) Then
            Return New ImageFormat(formatID)
        Else
            Return DirectCast(formats(formatID), ImageFormat)
        End If
    End Function
    
    '/// <summary>
    '/// Returns the ImageCodecInfo which corresponds
    '/// to the specified MIME type.
    '/// </summary>
    '/// <param name="mimeType">
    '/// The MIME type, e.g. "image/jpeg"
    '/// </param>
    '/// <returns>
    '/// The ImageCodecInfo for the MIME type.
    '/// </returns>
    Public Shared Function CodecFromMime(ByVal mimeType As String) As _
        ImageCodecInfo
        If mimeType Is Nothing OrElse 0 = mimeType.Length Then
            Throw New ArgumentNullException("mimeType")
        End If
        
        Dim i As Integer
        For i = 0 To codecs.Length - 1
            If 0 = String.Compare(codecs(i).MimeType, mimeType, true) Then
                Return codecs(i)
            End If
        Next
        
        Return Nothing
    End Function
    
    '/// <summary>
    '/// Returns the ImageFormat which corresponds
    '/// to the specified MIME type.
    '/// </summary>
    '/// <param name="mimeType">
    '/// The MIME type, e.g. "image/jpeg"
    '/// </param>
    '/// <returns>
    '/// The ImageFormat for the MIME type.
    '/// </returns>
    Public Shared Function FromMime(ByVal mimeType As String) As ImageFormat
        If mimeType Is Nothing OrElse 0 = mimeType.Length Then
            Throw New ArgumentNullException("mimeType")
        End If
        
        Dim info As ImageCodecInfo = CodecFromMime(mimeType)
        If info Is Nothing Then
            Return Nothing
        Else
            Return FromID(info.FormatID)
        End If
    End Function
    
    '/// <summary>
    '/// Returns an ImageCodecInfo which corresponds
    '/// to the extension of the supplied filename.
    '/// </summary>
    '/// <param name="filename">
    '/// The filename or extension of the image.
    '/// </param>
    '/// <returns>
    '/// The ImageCodecInfo for the filename.
    '/// </returns>
    Public Shared Function CodecFromExtension(ByVal filename As String) As _
        ImageCodecInfo
        If filename Is Nothing OrElse 0 = filename.Length Then
            Throw New ArgumentNullException("filename")
        End If
        
        Dim index As Integer = filename.LastIndexOf("."c)
        If -1 = index Then Return Nothing
        
        Dim ext As String = "*." & filename.Substring(index + 1)
        Dim i As Integer
        For i = 0 To codecs.Length - 1
            Dim extensions() As String = codecs(i).FilenameExtension.Split(";"c)
            Dim j As Integer
            For j = 0 To extensions.Length - 1
                If 0 = String.Compare(extensions(j), ext, true) Then
                    Return codecs(i)
                End If
            Next
        Next
        
        Return Nothing
    End Function
    
    '/// <summary>
    '/// Returns an ImageFormat which corresponds
    '/// to the extension of the supplied filename.
    '/// </summary>
    '/// <param name="filename">
    '/// The filename or extension of the image.
    '/// </param>
    '/// <returns>
    '/// The ImageFormat for the filename.
    '/// </returns>
    Public Shared Function FromExtension(ByVal filename As String) As _
        ImageFormat
        If filename Is Nothing OrElse 0 = filename.Length Then
            Throw New ArgumentNullException("filename")
        End If
        
        Dim info As ImageCodecInfo = CodecFromExtension(filename)
        If info Is Nothing Then
            Return Nothing
        Else
            Return FromID(info.FormatID)
        End If
    End Function
    
    '/// <summary>
    '/// No need to create an instance of this class.
    '/// </summary>
    Private Sub New()
    End Sub
End Class


' *******************
' * SAMPLE USAGE
' *******************

Option Explicit
Option Strict

Imports System
Imports System.Collections
Imports System.Reflection
Imports System.Drawing.Imaging

Class App
    Shared Sub Main()
        Try
            Dim file As String
            Dim index As Integer
            Dim codec As ImageCodecInfo
            
            do
                Console.Write("Enter a file name or MIME type: ")
                file = Console.ReadLine()
                
                If Not (file Is Nothing) AndAlso 0 < file.Length Then
                    index = file.IndexOf("/"c)
                    If -1 = index Then
                        codec = ImageFormatUtils.CodecFromExtension(file)
                    Else
                        codec = ImageFormatUtils.CodecFromMime(file)
                    End If
                    
                    If codec Is Nothing Then
                        Console.WriteLine("Unknown format.")
                    Else
                        WriteCodec(codec)
                    End If
                    
                    Console.WriteLine()
                End If
            Loop While Not(file Is Nothing) AndAlso 0 < file.Length
            
        Catch ex As Exception
            Console.WriteLine(ex)
        End Try
    End Sub
    
    Shared Sub WriteCodec(ByVal codec As ImageCodecInfo)
        If codec Is Nothing Then Throw New ArgumentNullException("codec")
        
        Console.WriteLine("Format: {0}", ImageFormatUtils.FromID(codec.FormatID) _
            )
        Console.WriteLine("Name: {0}", codec.CodecName)
        Console.WriteLine("DLL: {0}", codec.DllName)
        Console.WriteLine("Version: {0}", codec.Version)
        Console.WriteLine("Extension: {0}", codec.FilenameExtension)
        Console.WriteLine("MIME: {0}", codec.MimeType)
    End Sub
End Class
Richard Deeming
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap