C# 如何测试文件是否为 jpeg?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/772388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# How can I test a file is a jpeg?
提问by
Using C# how can I test a file is a jpeg? Should I check for a .jpg extension?
使用 C# 如何测试文件是 jpeg?我应该检查 .jpg 扩展名吗?
Thanks
谢谢
采纳答案by Dirk Vollmar
Several options:
几个选项:
You can check for the file extension:
您可以检查文件扩展名:
static bool HasJpegExtension(string filename)
{
// add other possible extensions here
return Path.GetExtension(filename).Equals(".jpg", StringComparison.InvariantCultureIgnoreCase)
|| Path.GetExtension(filename).Equals(".jpeg", StringComparison.InvariantCultureIgnoreCase);
}
or check for the correct magic numberin the header of the file:
或检查文件标题中的正确幻数:
static bool HasJpegHeader(string filename)
{
using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open, FileAccess.Read)))
{
UInt16 soi = br.ReadUInt16(); // Start of Image (SOI) marker (FFD8)
UInt16 marker = br.ReadUInt16(); // JFIF marker (FFE0) or EXIF marker(FFE1)
return soi == 0xd8ff && (marker & 0xe0ff) == 0xe0ff;
}
}
Another option would be to load the image and check for the correct type. However, this is less efficient (unless you are going to load the image anyway) but will probably give you the most reliable result (Be aware of the additional cost of loading and decompression as well as possible exception handling):
另一种选择是加载图像并检查正确的类型。但是,这效率较低(除非您无论如何都要加载图像)但可能会给您最可靠的结果(请注意加载和解压缩以及可能的异常处理的额外成本):
static bool IsJpegImage(string filename)
{
try
{
using (System.Drawing.Image img = System.Drawing.Image.FromFile(filename))
{
// Two image formats can be compared using the Equals method
// See http://msdn.microsoft.com/en-us/library/system.drawing.imaging.imageformat.aspx
//
return img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
catch (OutOfMemoryException)
{
// Image.FromFile throws an OutOfMemoryException
// if the file does not have a valid image format or
// GDI+ does not support the pixel format of the file.
//
return false;
}
}
回答by Galwegian
You can use the Path.GetExtension Method.
您可以使用Path.GetExtension 方法。
回答by Brian Ensink
You could find documentation on the jpeg file format, specifically the header information. Then try to read this information from the file and compare it to the expected jpeg header bytes.
您可以找到有关 jpeg 文件格式的文档,特别是标题信息。然后尝试从文件中读取此信息并将其与预期的 jpeg 标头字节进行比较。
回答by Program.X
The code here:
这里的代码:
http://mark.michaelis.net/Blog/RetrievingMetaDataFromJPEGFilesUsingC.aspx
http://mark.michaelis.net/Blog/RetrievingMetaDataFromJPEGFilesUsingC.aspx
Shows you how to get the Meta Data. I guess that would throw an exception if your image wasn't a valid JPEG.
向您展示如何获取元数据。如果您的图像不是有效的 JPEG,我想这会引发异常。
回答by Shaun Humphries
Once you have the extension you could use a regular expression to validate it.
一旦你有了扩展,你就可以使用正则表达式来验证它。
^.*\.(jpg|JPG)$
回答by Simon Gibbs
Open the file as a stream and look for the magic numberfor JPEG.
将文件作为流打开并查找JPEG的幻数。
JPEG image files begin with FF D8 and end with FF D9. JPEG/JFIF files contain the ASCII code for 'JFIF' (4A 46 49 46) as a null terminated string. JPEG/Exif files contain the ASCII code for 'Exif' (45 78 69 66) also as a null terminated string
JPEG 图像文件以 FF D8 开头,以 FF D9 结尾。JPEG/JFIF 文件包含 'JFIF' (4A 46 49 46) 的 ASCII 代码作为空终止字符串。JPEG/Exif 文件包含 'Exif' (45 78 69 66) 的 ASCII 代码,也作为空终止字符串
回答by Lee
You could try loading the file into an Image and then check the format
您可以尝试将文件加载到图像中,然后检查格式
Image img = Image.FromFile(filePath);
bool isBitmap = img.RawFormat.Equals(ImageFormat.Jpeg);
Alternatively you could open the file and check the header to get the type
或者,您可以打开文件并检查标题以获取类型
回答by Mitch Wheat
Read the header bytes. This article contains info on several common image formats, including JPEG:
读取头字节。本文包含有关几种常见图像格式的信息,包括 JPEG:
回答by Steve Dunn
Checking the file extension is not enough as the filename might be lying.
检查文件扩展名是不够的,因为文件名可能在说谎。
A quick and dirty way is to try and load the image using the Image class and catching any exceptions:
一种快速而肮脏的方法是尝试使用 Image 类加载图像并捕获任何异常:
Image image = Image.FromFile(@"c:\temp\test.jpg");
This isn't ideal as you could get any kind of exception, such as OutOfMemoryException, FileNotFoundException, etc. etc.
这并不理想,因为您可能会遇到任何类型的异常,例如 OutOfMemoryException、FileNotFoundException 等。
The most thorough way is to treat the file as binary and ensure the header matches the JPG format. I'm sure it's described somewhere.
最彻底的方法是将文件视为二进制文件并确保标头与 JPG 格式匹配。我确定它在某处被描述过。
回答by Skizz
The best way would to try and create an image from it using the Drawing.Bitmap (string) constructor and see if it fails to do so or throws an exception. The problem with some of the answers are this: firstly, the extension is purely arbitrary, it could be jpg, jpeg, jpe, bob, tim, whatever. Secondly, just using the header isn't enough to be 100% sure. It can definitely determine that a file isn't a jpeg but can't guarantee that a file is a jpeg, an arbitrary binary file could have the same byte sequence at the start.
最好的方法是尝试使用 Drawing.Bitmap (string) 构造函数从中创建图像,并查看它是否无法这样做或引发异常。一些答案的问题是:首先,扩展名纯粹是任意的,它可以是 jpg、jpeg、jpe、bob、tim 等等。其次,仅使用标题还不足以保证 100% 的确定。它可以肯定地确定一个文件不是 jpeg,但不能保证一个文件是 jpeg,任意二进制文件在开始时可能具有相同的字节序列。
回答by Armbrat
This will loop through each file in the current directory and will output if any found files with JPG or JPEG extension are Jpeg images.
这将遍历当前目录中的每个文件,并输出任何找到的带有 JPG 或 JPEG 扩展名的文件是 Jpeg 图像。
foreach (FileInfo f in new DirectoryInfo(".").GetFiles())
{
if (f.Extension.ToUpperInvariant() == ".JPG"
|| f.Extension.ToUpperInvariant() == ".JPEG")
{
Image image = Image.FromFile(f.FullName);
if (image.RawFormat == ImageFormat.Jpeg)
{
Console.WriteLine(f.FullName + " is a Jpeg image");
}
}
}