确定的图像的文件类型文件类型、图像

2023-09-02 10:24:19 作者:半世倾城╮只为一人醉°

我下载一些图片,从一个服务,它并不总是包含的内容类型,并没有规定我下载该文件的扩展名(唉,不要问)。

I'm downloading some images from a service that doesn't always include a content-type and doesn't provide an extension for the file I'm downloading (ugh, don't ask).

什么是确定在.NET中的图像格式的最佳方法是什么?

What's the best way to determine the image format in .NET?

这是阅读这些下载的图片的应用程序需要有一个适当的文件扩展名或所有的地狱破散。

The application that is reading these downloaded images needs to have a proper file extension or all hell breaks loose.

推荐答案

一个可能更容易的方法是使用Image.FromFile(),然后使用RawFormat属性,因为它已经知道魔术位的标头的最常见的格式,如:

A probably easier approach would be to use Image.FromFile() and then use the RawFormat property, as it already knows about the magic bits in the headers for the most common formats, like this:

Image i = Image.FromFile("c:\foo");
if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(i.RawFormat)) 
    MessageBox.Show("JPEG");
else if (System.Drawing.Imaging.ImageFormat.Gif.Equals(i.RawFormat))
    MessageBox.Show("GIF");
//Same for the rest of the formats