2009-08-26 178 views

回答

30

这里的一些老代码,我发现应该做的伎俩:

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

这就需要实际打开和测试图像 - 文件扩展名被忽略。假设你打开文件,这比信任一个文件扩展名要稳健得多。

如果你不打开文件,没有比字符串比较“更快”(在性能意义上) - 当然不会调用操作系统来获取文件扩展名映射。

+4

为什么你需要行'图形gInput = Graphics.FromImage(imgInput);'? 'gInput'根本不使用。 – 2014-09-25 08:15:49

+0

也许,他想把所有这些都放在Try-Catch中,看看它是否有效。 – RealityDysfunction 2014-10-08 15:58:49

+0

尽管如此,这对于“另存为...”场景来说是无用的。 – Nyerguds 2015-02-26 09:55:52

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

如果打开文件不可行,这是更好的选择。例如,加载非常大的图像可能会导致“OutOfMemory”异常。这不是很健壮,对许多用例都会这样做。 – TEK 2016-05-09 15:56:20

5
private static ImageFormat GetImageFormat(string format) 
    { 
     ImageFormat imageFormat = null; 

     try 
     { 
      var imageFormatConverter = new ImageFormatConverter(); 
      imageFormat = (ImageFormat)imageFormatConverter.ConvertFromString(format); 
     } 
     catch (Exception) 
     { 

      throw; 
     } 

     return imageFormat; 
    } 
+0

我不明白为什么这是upvoted! imageFormatConverter.ConvertFromString继承自TypeConverter并始终返回null或引发NotSupportedException! [见此](https://stackoverflow.com/a/3594313/2803565) – 2017-12-10 11:45:09