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

前端 未结 11 1011
陌清茗
陌清茗 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:21

    Complete solution in C# is here:

    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 result = dlg.ShowDialog();
    
        // Process open file dialog box results 
        if (result == true)
        {
           // Open document 
           string fileName  = dlg.FileName;
           // Do something with fileName  
        }
    } 
    

提交回复
热议问题