检查文件扩展名是否为图像的好方法 [英] Good way to check if file extension is of an image or not
本文介绍了检查文件扩展名是否为图像的好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有此文件类型过滤器:
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:.NET中是否有任何默认过滤器或免费的库?
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...)
}
使用Jeroen Vannevel EndsWith的解决方案.我认为可以.
Solution using Jeroen Vannevel EndsWith. I think it is ok.
public static bool IsImageExtension(string ext)
{
return imagesTypes.Contains(ext);
}
推荐答案
您可以使用.endsWith(ext)
.不过,这不是一种非常安全的方法:我可以将"bla.jpg"重命名为"bla.png",并且仍然是jpg文件.
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;
这篇关于检查文件扩展名是否为图像的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文