我有这个代码,我怎么能让它接受所有典型的图像格式?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,但其他类型呢?


当前回答

对于图像,您可以从GDI (System.Drawing)获得可用的编解码器,并通过一些工作来构建您的列表。这将是最灵活的方式。

ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

其他回答

我最喜欢汤姆·浮士德的回答。下面是他的解决方案的c#版本,但简化了一些事情。

var codecs = ImageCodecInfo.GetImageEncoders(); 
var codecFilter = "Image Files|"; 
foreach (var codec in codecs) 
{
    codecFilter += codec.FilenameExtension + ";"; 
} 
dialog.Filter = codecFilter;

写出应用程序需要的类型。(ref FileDialog.Filter)。以下是最常见的图像格式。

private static string GetImageFilter()
{
    return
        "All Files (*.*)|*.*" +
        "|All Pictures (*.emf;*.wmf;*.jpg;*.jpeg;*.jfif;*.jpe;*.png;*.bmp;*.dib;*.rle;*.gif;*.emz;*.wmz;*.tif;*.tiff;*.svg;*.ico)" +
            "|*.emf;*.wmf;*.jpg;*.jpeg;*.jfif;*.jpe;*.png;*.bmp;*.dib;*.rle;*.gif;*.emz;*.wmz;*.tif;*.tiff;*.svg;*.ico" +
        "|Windows Enhanced Metafile (*.emf)|*.emf" +
        "|Windows Metafile (*.wmf)|*.wmf" +
        "|JPEG File Interchange Format (*.jpg;*.jpeg;*.jfif;*.jpe)|*.jpg;*.jpeg;*.jfif;*.jpe" +
        "|Portable Network Graphics (*.png)|*.png" +
        "|Bitmap Image File (*.bmp;*.dib;*.rle)|*.bmp;*.dib;*.rle" +
        "|Compressed Windows Enhanced Metafile (*.emz)|*.emz" +
        "|Compressed Windows MetaFile (*.wmz)|*.wmz" +
        "|Tag Image File Format (*.tif;*.tiff)|*.tif;*.tiff" +
        "|Scalable Vector Graphics (*.svg)|*.svg" +
        "|Icon (*.ico)|*.ico";
}

示例使用

设置FilterIndex = 2以预选“所有图片”。不要设置openFileDialog。除非你有一个很好的理由。

void OpenImageFile()
{
    var openFileDialog  = new OpenFileDialog
    {
        Filter = GetImageFilter(),
        FilterIndex = 2,
        RestoreDirectory = true
    };
    DialogResult result = openFileDialog.ShowDialog();

    // do something with your file
    // bool resultOk = (result == System.Windows.Forms.DialogResult.OK);
    // string filePath = openFileDialog.FileName;
    // ...
}

必须包含所有图像类型扩展名,并允许将所有文件作为一个选项。

所有文件|。|所有图片|.jpg;.jpeg;.png;.gif;.tif;.bmp|JPEG图片|.jpg|PNG图片|.png";

完整的c#解决方案在这里:

private void btnSelectImage_Click(object sender, RoutedEventArgs e)
{
    // Configure open file dialog box 
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
    dlg.Filter = "";

    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
    string sep = string.Empty;

    foreach (var c in codecs)
    {
       string codecName = c.CodecName.Substring(8).Replace("Codec", "Files").Trim();
       dlg.Filter = String.Format("{0}{1}{2} ({3})|{3}", dlg.Filter, sep, codecName, c.FilenameExtension);
       sep = "|";
    }

    dlg.Filter = String.Format("{0}{1}{2} ({3})|{3}", dlg.Filter, sep, "All Files", "*.*"); 

    dlg.DefaultExt = ".png"; // Default file extension 

    // Show open file dialog box 
    Nullable<bool> result = dlg.ShowDialog();

    // Process open file dialog box results 
    if (result == true)
    {
       // Open document 
       string fileName  = dlg.FileName;
       // Do something with fileName  
    }
} 

使用此方法返回一个与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;
        }

结果如下所示: