我有这个代码,我怎么能让它接受所有典型的图像格式?Png, jpeg, jpg, gif ?

以下是我目前所了解到的:

public void EncryptFile()
{            
    OpenFileDialog dialog = new OpenFileDialog();
    dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
    dialog.InitialDirectory = @"C:\";
    dialog.Title = "Please select an image file to encrypt.";

    if (dialog.ShowDialog() == DialogResult.OK)
    {
        //Encrypt the selected file. I'll do this later. :)
    }             
}

注意,过滤器被设置为.txt文件。我可以更改为PNG,但其他类型呢?


当前回答

使用此方法返回一个与Filter兼容的字符串,该字符串由支持当前系统理解的图像格式的ImageCodecInfo构建。

        /// <summary>
        /// Get the Filter string for all supported image types.
        /// To be used in the FileDialog class Filter Property.
        /// </summary>
        /// <returns></returns>
        public static string GetImageFilter()
        {
            string imageExtensions = string.Empty;
            string separator = "";
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            Dictionary<string, string> imageFilters = new Dictionary<string, string>();
            foreach (ImageCodecInfo codec in codecs)
            {
                imageExtensions = $"{imageExtensions}{separator}{codec.FilenameExtension.ToLower()}";
                separator = ";";
                imageFilters.Add($"{codec.FormatDescription} files ({codec.FilenameExtension.ToLower()})", codec.FilenameExtension.ToLower());
            }
            string result = string.Empty;
            separator = "";
            foreach (KeyValuePair<string, string> filter in imageFilters)
            {
                result += $"{separator}{filter.Key}|{filter.Value}";
                separator = "|";
            }
            if (!string.IsNullOrEmpty(imageExtensions))
            {
                result += $"{separator}Image files|{imageExtensions}";
            }
            return result;
        }

结果如下所示:

其他回答

对于那些不想每次都记住语法的人,这里有一个简单的封装:

public class FileDialogFilter : List<string>
{
    public string Explanation { get; }

    public FileDialogFilter(string explanation, params string[] extensions)
    {
        Explanation = explanation;
        AddRange(extensions);
    }

    public string GetFileDialogRepresentation()
    {
        if (!this.Any())
        {
            throw new ArgumentException("No file extension is defined.");
        }

        StringBuilder builder = new StringBuilder();

        builder.Append(Explanation);

        builder.Append(" (");
        builder.Append(String.Join(", ", this));
        builder.Append(")");

        builder.Append("|");
        builder.Append(String.Join(";", this));

        return builder.ToString();
    }
}

public class FileDialogFilterCollection : List<FileDialogFilter>
{
    public string GetFileDialogRepresentation()
    {
        return String.Join("|", this.Select(filter => filter.GetFileDialogRepresentation()));
    }
}

用法:

FileDialogFilter filterImage = new FileDialogFilter("Image Files", "*.jpeg", "*.bmp");
FileDialogFilter filterOffice = new FileDialogFilter("Office Files", "*.doc", "*.xls", "*.ppt");

FileDialogFilterCollection filters = new FileDialogFilterCollection
{
    filterImage,
    filterOffice
};

OpenFileDialog fileDialog = new OpenFileDialog
{
    Filter = filters.GetFileDialogRepresentation()
};

fileDialog.ShowDialog();

只是一个关于使用字符串的necrocomment。Join和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()));

使用此方法返回一个与Filter兼容的字符串,该字符串由支持当前系统理解的图像格式的ImageCodecInfo构建。

        /// <summary>
        /// Get the Filter string for all supported image types.
        /// To be used in the FileDialog class Filter Property.
        /// </summary>
        /// <returns></returns>
        public static string GetImageFilter()
        {
            string imageExtensions = string.Empty;
            string separator = "";
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            Dictionary<string, string> imageFilters = new Dictionary<string, string>();
            foreach (ImageCodecInfo codec in codecs)
            {
                imageExtensions = $"{imageExtensions}{separator}{codec.FilenameExtension.ToLower()}";
                separator = ";";
                imageFilters.Add($"{codec.FormatDescription} files ({codec.FilenameExtension.ToLower()})", codec.FilenameExtension.ToLower());
            }
            string result = string.Empty;
            separator = "";
            foreach (KeyValuePair<string, string> filter in imageFilters)
            {
                result += $"{separator}{filter.Key}|{filter.Value}";
                separator = "|";
            }
            if (!string.IsNullOrEmpty(imageExtensions))
            {
                result += $"{separator}Image files|{imageExtensions}";
            }
            return result;
        }

结果如下所示:

要过滤图像文件,请使用下面的代码示例。

//Create a new instance of openFileDialog
OpenFileDialog res = new OpenFileDialog();

//Filter
res.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.gif;*.tif;...";

//When the user select the file
if (res.ShowDialog() == DialogResult.OK)
{
   //Get the file's path
   var filePath = res.FileName;
   //Do something
   ....
}

下面是一个ImageCodecInfo建议的例子(在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", "*.*")

它是这样的: