Good way to check if file extension is of an image or not

ぐ巨炮叔叔 提交于 2019-12-20 12:09:58

问题


I have this file types Filters:

    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: Is there any default filters in .NET or a free library for that?

I need a static method that checks if a string is an image or not. How would you solve this?

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

Solution using Jeroen Vannevel EndsWith. I think it is ok.

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

回答1:


You could use .endsWith(ext). It's not a very secure method though: I could rename 'bla.jpg' to 'bla.png' and it would still be a jpg file.

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

This provides a more secure solution:

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



回答2:


private static readonly string[] _validExtensions = {"jpg","bmp","gif","png"}; //  etc

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

If you want to be able to make the list configurable at runtime without recompiling, add something like:

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



回答3:


This method automatically creates a filter for the OpenFileDialog. It uses the informations of the image decoders supported by Windows. It also adds information of "unknown" image formats (see default case of the switch statement).

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

Use it like this:

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

The code above (slightly modified) can be used to find available image file extensions. In order to test if a given file extension denotes an image, I would put the valid extension in a HashSet. HashSets have an
O(1) access time! Make sure to choose a case insensitive string comparer. Since the file extensions do not contain accented or non Latin letters, the culture can safely be ignored. Therefore I use an ordinal string comparison.

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

And test if a filename is an image:

string extension = Path.GetExtension(filename);
bool isImage = imageExtensions.Contains(extension);



回答4:


An option would be to have a list of all possible valid image extensions, then that method would only check if the supplied extension is within that collection:

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

Then in the validation you just check against that:

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



回答5:


I just had to do something similiar. Here is my solution:

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


来源:https://stackoverflow.com/questions/17736160/good-way-to-check-if-file-extension-is-of-an-image-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!