有没有快速的方法来获取与特定文件扩展名关联的ImageFormat对象?我正在寻找比每种格式的字符串比较更快的方法。从文件扩展名获取ImageFormat
回答
这里的一些老代码,我发现应该做的伎俩:
string InputSource = "mypic.png";
System.Drawing.Image imgInput = System.Drawing.Image.FromFile(InputSource);
Graphics gInput = Graphics.fromimage(imgInput);
Imaging.ImageFormat thisFormat = imgInput.RawFormat;
这就需要实际打开和测试图像 - 文件扩展名被忽略。假设你打开文件,这比信任一个文件扩展名要稳健得多。
如果你不打开文件,没有比字符串比较“更快”(在性能意义上) - 当然不会调用操作系统来获取文件扩展名映射。
看到文件关联的CodeProject上的文章http://www.codeproject.com/KB/dotnet/System_File_Association.aspx
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();
}
}
如果打开文件不可行,这是更好的选择。例如,加载非常大的图像可能会导致“OutOfMemory”异常。这不是很健壮,对许多用例都会这样做。 – TEK 2016-05-09 15:56:20
private static ImageFormat GetImageFormat(string format)
{
ImageFormat imageFormat = null;
try
{
var imageFormatConverter = new ImageFormatConverter();
imageFormat = (ImageFormat)imageFormatConverter.ConvertFromString(format);
}
catch (Exception)
{
throw;
}
return imageFormat;
}
我不明白为什么这是upvoted! imageFormatConverter.ConvertFromString继承自TypeConverter并始终返回null或引发NotSupportedException! [见此](https://stackoverflow.com/a/3594313/2803565) – 2017-12-10 11:45:09
- 1. 获取文件扩展名
- 2. 如何从没有扩展名的文件名获取文件扩展名?
- 3. 从文件获取扩展
- 4. 从System.Drawing.Image.RawFormat获取ImageFormat
- 5. 获取除扩展名外没有扩展名的文件名
- 6. 从URL和带文件扩展名获取文件名
- 7. 获取文件的扩展名,但无法获取文件名
- 8. 从文件名中获取文件名和扩展名没有文件名
- 9. 获取Php文件/图像扩展名
- 10. 获取文件的扩展名(编辑)
- 11. Primefaces FileUpload获取文件扩展名
- 12. FileUpload获取文件扩展名
- 13. Node.js获取文件扩展名
- 14. 获取文件扩展名 - jquery
- 15. 使用preg_replace获取文件扩展名
- 16. 在java中获取文件扩展名
- 17. 获取文件扩展名C错误
- 18. 获取文件扩展名C
- 19. 获取扩展类的文件名
- 20. Nodejs获取文件扩展名
- 21. Android - 如何获取文件扩展名?
- 22. asp.net mvc HttpPostedFileBase获取文件扩展名
- 23. Smarty获取文件扩展名
- 24. PHP,获取文件名没有扩展
- 25. Angularjs如何获取文件扩展名?
- 26. php:从损坏的文件中获取文件扩展名
- 27. 从file_get_contents获得文件扩展名
- 28. 从* .gz扩展名中提取文件
- 29. 如何从URL中获取文件名和扩展名?
- 30. 从wget响应中获取“文件名”和扩展名
为什么你需要行'图形gInput = Graphics.FromImage(imgInput);'? 'gInput'根本不使用。 – 2014-09-25 08:15:49
也许,他想把所有这些都放在Try-Catch中,看看它是否有效。 – RealityDysfunction 2014-10-08 15:58:49
尽管如此,这对于“另存为...”场景来说是无用的。 – Nyerguds 2015-02-26 09:55:52