我有这个代码,我怎么能让它接受所有典型的图像格式?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,但其他类型呢?
完整的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
}
}
下面是一个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", "*.*")
它是这样的:
完整的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
}
}