2009-08-26 31 views
21

特定のファイル拡張子に関連付けられた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; 

これは、実際に画像を開くとテストが必要です。

答えて

30

をCodeProjectの記事を参照してください。とにかくファイルを開いていると仮定すると、これはファイル拡張子を信頼するよりはるかに堅牢です。

ファイルを開いていない場合は、ファイルの拡張子のマッピングを取得するためにOSを呼び出すのではなく、文字列の比較よりも「パフォーマンスが速い」ものはありません。 `;

+4

は、なぜあなたはライン'グラフィックス関数ginput = Graphics.FromImage(imgInput)が必要ですか? 'gInput'はまったく使われません。 –

+0

たぶん、彼はTry-Catchにすべてを入れて、それが機能するかどうかを見たいと思っていました。 – RealityDysfunction

+0

これは、「別名で保存...」シナリオではむしろ役に立たない。 – Nyerguds

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

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) –

関連する問題