23

我有这个文件类型过滤器:

    public const string Png = "PNG Portable Network Graphics (*.png)|" + "*.png";
    public const string Jpg = "JPEG File Interchange Format (*.jpg *.jpeg *jfif)|" + "*.jpg;*.jpeg;*.jfif";
    public const string Bmp = "BMP Windows Bitmap (*.bmp)|" + "*.bmp";
    public const string Tif = "TIF Tagged Imaged File Format (*.tif *.tiff)|" + "*.tif;*.tiff";
    public const string Gif = "GIF Graphics Interchange Format (*.gif)|" + "*.gif";
    public const string AllImages = "Image file|" + "*.png; *.jpg; *.jpeg; *.jfif; *.bmp;*.tif; *.tiff; *.gif";
    public const string AllFiles = "All files (*.*)" + "|*.*";

    static FilesFilters()
    {
        imagesTypes = new List<string>();
        imagesTypes.Add(Png);
        imagesTypes.Add(Jpg);
        imagesTypes.Add(Bmp);
        imagesTypes.Add(Tif);
        imagesTypes.Add(Gif);
   }

OBS:.NET 中是否有任何默认过滤器或免费库?

我需要一个静态方法来检查字符串是否是图像。你会如何解决这个问题?

    //ext == Path.GetExtension(yourpath)
    public static bool IsImageExtension(string ext)
    {
        return (ext == ".bmp" || .... etc etc...)
    }

使用 Jeroen Vannevel EndsWith 的解决方案。我认为没关系。

    public static bool IsImageExtension(string ext)
    {
        return imagesTypes.Contains(ext);
    }
4

5 回答 5

17

你可以使用.endsWith(ext). 虽然这不是一个非常安全的方法:我可以将“bla.jpg”重命名为“bla.png”,它仍然是一个 jpg 文件。

public static bool HasImageExtension(this string source){
 return (source.EndsWith(".png") || source.EndsWith(".jpg"));
}

提供了更安全的解决方案:

string InputSource = "mypic.png";
System.Drawing.Image imgInput = System.Drawing.Image.FromFile(InputSource);
Graphics gInput = Graphics.fromimage(imgInput);
Imaging.ImageFormat thisFormat = imgInput.rawformat;
于 2013-07-19T00:20:24.813 回答
16
private static readonly string[] _validExtensions = {"jpg","bmp","gif","png"}; //  etc

public static bool IsImageExtension(string ext)
{
    return _validExtensions.Contains(ext.ToLower());
}

如果您希望能够在运行时使列表可配置而无需重新编译,请添加以下内容:

private static string[] _validExtensions;

private static string[] ValidExtensions()
{
    if(_validExtensions==null)
    { 
        // load from app.config, text file, DB, wherever
    }
    return _validExtensions
}

public static bool IsImageExtension(string ext)
{
    return ValidExtensions().Contains(ext.ToLower());
}
于 2013-07-19T05:38:08.277 回答
5

一个选项是列出所有可能的有效图像扩展名,然后该方法将仅检查提供的扩展名是否在该集合中:

private static readonly HashSet<string> validExtensions = new HashSet<string>()
{
    "png",
    "jpg",
    "bmp"
    // Other possible extensions
};

然后在验证中,您只需检查一下:

public static bool IsImageExtension(string ext)
{
    return validExtensions.Contains(ext);
}
于 2013-07-19T00:28:07.183 回答
5

此方法会自动为OpenFileDialog. 它使用 Windows 支持的图像解码器的信息。它还添加了“未知”图像格式的信息(参见语句default的案例)。switch

private static string SupportedImageDecodersFilter()
{
    ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();

    string allExtensions = encoders
        .Select(enc => enc.FilenameExtension)
        .Aggregate((current, next) => current + ";" + next)
        .ToLowerInvariant();
    var sb = new StringBuilder(500)
        .AppendFormat("Image files  ({0})|{1}", allExtensions.Replace(";", ", "),
                      allExtensions);
    foreach (ImageCodecInfo encoder in encoders) {
        string ext = encoder.FilenameExtension.ToLowerInvariant();
        // ext = "*.bmp;*.dib;*.rle"           descr = BMP
        // ext = "*.jpg;*.jpeg;*.jpe;*.jfif"   descr = JPEG
        // ext = "*.gif"                       descr = GIF
        // ext = "*.tif;*.tiff"                descr = TIFF
        // ext = "*.png"                       descr = PNG

        string caption;
        switch (encoder.FormatDescription) {
            case "BMP":
                caption = "Windows Bitmap";
                break;
            case "JPEG":
                caption = "JPEG file";
                break;
            case "GIF":
                caption = "Graphics Interchange Format";
                break;
            case "TIFF":
                caption = "Tagged Image File Format";
                break;
            case "PNG":
                caption = "Portable Network Graphics";
                break;
            default:
                caption = encoder.FormatDescription;
                break;
        }
        sb.AppendFormat("|{0}  ({1})|{2}", caption, ext.Replace(";", ", "), ext);
    }
    return sb.ToString();
}

像这样使用它:

var dlg = new OpenFileDialog {
    Filter = SupportedImageDecodersFilter(),
    Multiselect = false,
    Title = "Choose Image"
};

上面的代码(稍作修改)可用于查找可用的图像文件扩展名。为了测试给定的文件扩展名是否表示图像,我会将有效的扩展名放在HashSet. HashSet 的
访问时间为 O(1)!确保选择不区分大小写的字符串比较器。由于文件扩展名不包含重音或非拉丁字母,因此可以安全地忽略文化。因此我使用序数字符串比较。

var imageExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
imageExtensions.Add(".png");
imageExtensions.Add(".bmp");
...

并测试文件名是否为图像:

string extension = Path.GetExtension(filename);
bool isImage = imageExtensions.Contains(extension);
于 2014-02-17T17:35:23.043 回答
4

我只需要做类似的事情。这是我的解决方案:

    private bool IsImage(string fileExtension)
    {
        return GetImageFileExtensions().Contains(fileExtension.ToLower()));
    }

    private static List<string> GetImageFileExtensions()
    {
        return ImageCodecInfo.GetImageEncoders()
                             .Select(c => c.FilenameExtension)
                             .SelectMany(e => e.Split(';'))
                             .Select(e => e.Replace("*", "").ToLower())
                             .ToList();            
    }
于 2019-02-23T22:13:08.863 回答