确定图像的文件类型 [英] Determine file type of an image

查看:28
本文介绍了确定图像的文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从一项并不总是包含内容类型的服务下载一些图像,并且没有为我正在下载的文件提供扩展名(呃,别问了).

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

这篇关于确定图像的文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆