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); }
If you are having trouble and want to check if you photo is a JPEG, look at the writing under the photo in its file name. If it ends . jpg or . jpeg- then the file is a JPEG and will upload.
Open a file in a Hex editor (or just a binary file viewer). PNG files start with 'PNG', . jpg files should have 'exif'or 'JFIF' somewhere in the beginning.
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;
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()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With