C# 将过滤器设置为 OpenFileDialog 以允许典型的图像格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2069048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting the filter to an OpenFileDialog to allow the typical image formats?
提问by Sergio Tapia
I have this code, how can I allow it to accept all typical image formats? PNG, JPEG, JPG, GIF?
我有这个代码,我怎样才能让它接受所有典型的图像格式?PNG、JPEG、JPG、GIF?
Here's what I have so far:
这是我到目前为止所拥有的:
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. :)
}
}
Notice that the filter is set to .txt files. I couldchange to PNG, but what of the other types?
请注意,过滤器设置为 .txt 文件。我可以更改为 PNG,但其他类型呢?
采纳答案by itowlson
回答by Muad'Dib
For images, you could get the available codecs from GDI (System.Drawing) and build your list from that with a little work. This would be the most flexible way to go.
对于图像,您可以从 GDI (System.Drawing) 获取可用的编解码器,并通过一些工作从中构建您的列表。这将是最灵活的方式。
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
回答by Tom Faust
Here's an example of the ImageCodecInfo suggestion (in VB):
这是 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", "*.*")
And it looks like this:
它看起来像这样:
回答by Developer
Complete solution in C# is here:
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
}
}
回答by Devam Mehta
Follow this pattern if you browsing for image files:
如果您浏览图像文件,请遵循以下模式:
dialog.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
回答by HermF
To filter images files, use this code sample.
要过滤图像文件,请使用此代码示例。
//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
....
}
回答by Anthony L. Gershman
Just a necrocomment for using string.Join and LINQ.
只是使用 string.Join 和 LINQ 的 necrocomment。
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()));
回答by Yusuf Tar?k Günayd?n
For those who don't want to remember the syntax everytime here is a simple encapsulation:
对于那些不想每次都记住语法的人,这里有一个简单的封装:
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()));
}
}
Usage:
用法:
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();
回答by NielW
I like Tom Faust's answer the best. Here's a C# version of his solution, but simplifying things a bit.
我最喜欢汤姆浮士德的回答。这是他的解决方案的 C# 版本,但稍微简化了一些事情。
var codecs = ImageCodecInfo.GetImageEncoders();
var codecFilter = "Image Files|";
foreach (var codec in codecs)
{
codecFilter += codec.FilenameExtension + ";";
}
dialog.Filter = codecFilter;
回答by vapcguy
This is extreme, but I built a dynamic, database-driven filter using a 2 column database table named FILE_TYPES, with field names EXTENSION and DOCTYPE:
这是极端的,但我使用名为 FILE_TYPES 的 2 列数据库表构建了一个动态的、数据库驱动的过滤器,字段名称为 EXTENSION 和 DOCTYPE:
---------------------------------
| EXTENSION | DOCTYPE |
---------------------------------
| .doc | Document |
| .docx | Document |
| .pdf | Document |
| ... | ... |
| .bmp | Image |
| .jpg | Image |
| ... | ... |
---------------------------------
Obviously I had many different types and extensions, but I'm simplifying it for this example. Here is my function:
显然我有许多不同的类型和扩展,但我在这个例子中简化了它。这是我的功能:
private static string GetUploadFilter()
{
// Desired format:
// "Document files (*.doc, *.docx, *.pdf)|*.doc;*.docx;*.pdf|"
// "Image files (*.bmp, *.jpg)|*.bmp;*.jpg|"
string filter = String.Empty;
string nameFilter = String.Empty;
string extFilter = String.Empty;
// Used to get extensions
DataTable dt = new DataTable();
dt = DataLayer.Get_DataTable("SELECT * FROM FILE_TYPES ORDER BY EXTENSION");
// Used to cycle through doctype groupings ("Images", "Documents", etc.)
DataTable dtDocTypes = new DataTable();
dtDocTypes = DataLayer.Get_DataTable("SELECT DISTINCT DOCTYPE FROM FILE_TYPES ORDER BY DOCTYPE");
// For each doctype grouping...
foreach (DataRow drDocType in dtDocTypes.Rows)
{
nameFilter = drDocType["DOCTYPE"].ToString() + " files (";
// ... add its associated extensions
foreach (DataRow dr in dt.Rows)
{
if (dr["DOCTYPE"].ToString() == drDocType["DOCTYPE"].ToString())
{
nameFilter += "*" + dr["EXTENSION"].ToString() + ", ";
extFilter += "*" + dr["EXTENSION"].ToString() + ";";
}
}
// Remove endings put in place in case there was another to add, and end them with pipe characters:
nameFilter = nameFilter.TrimEnd(' ').TrimEnd(',');
nameFilter += ")|";
extFilter = extFilter.TrimEnd(';');
extFilter += "|";
// Add the name and its extensions to our main filter
filter += nameFilter + extFilter;
extFilter = ""; // clear it for next round; nameFilter will be reset to the next DOCTYPE on next pass
}
filter = filter.TrimEnd('|');
return filter;
}
private void UploadFile(string fileType, object sender)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
string filter = GetUploadFilter();
dlg.Filter = filter;
if (dlg.ShowDialog().Value == true)
{
string fileName = dlg.FileName;
System.IO.FileStream fs = System.IO.File.OpenRead(fileName);
byte[] array = new byte[fs.Length];
// This will give you just the filename
fileName = fileName.Split('\')[fileName.Split('\').Length - 1];
...
Should yield a filter that looks like this:
应该产生一个看起来像这样的过滤器: