C# 从文件扩展名获取 ImageFormat
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1337750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get ImageFormat from File Extension
提问by Chris Dwyer
Is there quick way to get the ImageFormat object associated to a particular file extension? I'm looking for quicker than string comparisons for each format.
有没有快速的方法来获取与特定文件扩展名关联的 ImageFormat 对象?我正在为每种格式寻找比字符串比较更快的方法。
采纳答案by richardtallent
Here's some old code I found that should do the trick:
这是我发现应该可以解决的一些旧代码:
string InputSource = "mypic.png";
System.Drawing.Image imgInput = System.Drawing.Image.FromFile(InputSource);
Graphics gInput = Graphics.fromimage(imgInput);
Imaging.ImageFormat thisFormat = imgInput.RawFormat;
This requires actually opening and testing the image--the file extension is ignored. Assuming you are opening the file anyway, this is much more robust than trusting a file extension.
这需要实际打开和测试图像——忽略文件扩展名。假设您无论如何都在打开文件,这比信任文件扩展名要可靠得多。
If you aren't opening the files, there's nothing "quicker" (in a performance sense) than a string comparison--certainly not calling into the OS to get file extension mappings.
如果您不打开文件,则没有什么比字符串比较“更快”(在性能意义上)——当然不会调用操作系统来获取文件扩展名映射。
回答by Robert French
see the CodeProject article on File Associations http://www.codeproject.com/KB/dotnet/System_File_Association.aspx
请参阅有关文件关联的 CodeProject 文章http://www.codeproject.com/KB/dotnet/System_File_Association.aspx
回答by Ryan Williams
private static ImageFormat GetImageFormat(string fileName)
{
string extension = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(extension))
throw new ArgumentException(
string.Format("Unable to determine file extension for fileName: {0}", fileName));
switch (extension.ToLower())
{
case @".bmp":
return ImageFormat.Bmp;
case @".gif":
return ImageFormat.Gif;
case @".ico":
return ImageFormat.Icon;
case @".jpg":
case @".jpeg":
return ImageFormat.Jpeg;
case @".png":
return ImageFormat.Png;
case @".tif":
case @".tiff":
return ImageFormat.Tiff;
case @".wmf":
return ImageFormat.Wmf;
default:
throw new NotImplementedException();
}
}
回答by Barda
private static ImageFormat GetImageFormat(string format)
{
ImageFormat imageFormat = null;
try
{
var imageFormatConverter = new ImageFormatConverter();
imageFormat = (ImageFormat)imageFormatConverter.ConvertFromString(format);
}
catch (Exception)
{
throw;
}
return imageFormat;
}