首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将过滤器设置为OpenFileDialog以允许典型的图像格式?

将过滤器设置为OpenFileDialog以允许典型的图像格式?
EN

Stack Overflow用户
提问于 2010-01-15 10:27:19
回答 12查看 435.5K关注 0票数 249

我有这个代码,我怎么能让它接受所有典型的图像格式呢?PNG、JPEG、JPG、GIF?

这是我到目前为止所知道的:

代码语言:javascript
复制
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文件。I可以将更改为PNG,但其他类型怎么办?

EN

回答 12

Stack Overflow用户

回答已采纳

发布于 2010-01-15 10:37:07

the docs中,您需要的筛选器语法如下:

代码语言:javascript
复制
Office Files|*.doc;*.xls;*.ppt

即用分号分隔多个扩展名--因此,Image Files|*.jpg;*.jpeg;*.png;...

票数 311
EN

Stack Overflow用户

发布于 2011-12-16 07:11:58

以下是ImageCodecInfo建议的示例(在VB中):

代码语言:javascript
复制
   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", "*.*")

它看起来像这样:

票数 79
EN

Stack Overflow用户

发布于 2012-02-07 20:50:35

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

代码语言:javascript
复制
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  
    }
} 
票数 48
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2069048

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档