Setting the filter to an OpenFileDialog to allow the typical image formats?

前端 未结 11 956
陌清茗
陌清茗 2020-12-22 16:07

I have this code, how can I allow it to accept all typical image formats? PNG, JPEG, JPG, GIF?

Here\'s what I have so far:

public void EncryptFile()
         


        
相关标签:
11条回答
  • 2020-12-22 16:31

    Here's an example of the ImageCodecInfo suggestion (in VB):

       Imports System.Drawing.Imaging
            ...            
    
            Dim ofd as new OpenFileDialog()
            ofd.Filter = ""
            Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()
            Dim sep As String = String.Empty
            For Each c As ImageCodecInfo In codecs
                Dim codecName As String = c.CodecName.Substring(8).Replace("Codec", "Files").Trim()
                ofd.Filter = String.Format("{0}{1}{2} ({3})|{3}", ofd.Filter, sep, codecName, c.FilenameExtension)
                sep = "|"
            Next
            ofd.Filter = String.Format("{0}{1}{2} ({3})|{3}", ofd.Filter, sep, "All Files", "*.*")
    

    And it looks like this:

    enter image description here

    0 讨论(0)
  • 2020-12-22 16:34

    I like Tom Faust's answer the best. Here's a C# version of his solution, but simplifying things a bit.

    var codecs = ImageCodecInfo.GetImageEncoders(); 
    var codecFilter = "Image Files|"; 
    foreach (var codec in codecs) 
    {
        codecFilter += codec.FilenameExtension + ";"; 
    } 
    dialog.Filter = codecFilter;
    
    0 讨论(0)
  • 2020-12-22 16:35

    Follow this pattern if you browsing for image files:

    dialog.Filter =  "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
    
    0 讨论(0)
  • 2020-12-22 16:35

    In order to match a list of different categories of file, you can use the filter like this:

            var dlg = new Microsoft.Win32.OpenFileDialog()
            {
                DefaultExt = ".xlsx",
                Filter = "Excel Files (*.xls, *.xlsx)|*.xls;*.xlsx|CSV Files (*.csv)|*.csv"
            };
    
    0 讨论(0)
  • 2020-12-22 16:47

    Just a necrocomment for using string.Join and LINQ.

    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
    dlgOpenMockImage.Filter = string.Format("{0}| All image files ({1})|{1}|All files|*", 
        string.Join("|", codecs.Select(codec => 
        string.Format("{0} ({1})|{1}", codec.CodecName, codec.FilenameExtension)).ToArray()),
        string.Join(";", codecs.Select(codec => codec.FilenameExtension).ToArray()));
    
    0 讨论(0)
提交回复
热议问题