检查文件扩展名是否为图像的好方法

时间:2013-07-19 00:17:41

标签: c# file-extension openfiledialog filefilter

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

    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);
    }

5 个答案:

答案 0 :(得分:15)

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

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

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

string InputSource = "mypic.png";
System.Drawing.Image imgInput = System.Drawing.Image.FromFile(InputSource);
Graphics gInput = Graphics.fromimage(imgInput);
Imaging.ImageFormat thisFormat = imgInput.rawformat;

答案 1 :(得分:14)

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());
}

答案 2 :(得分: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中。 HashSets有一个 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);

答案 3 :(得分:4)

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

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);
}

答案 4 :(得分:1)

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

Error in if (k <= 0.8 && any(rr > (strwidth("W") * fsize/2))) rr <- rr/max(rr) *  : 
  missing value where TRUE/FALSE needed