我想要执行以下操作的代码:
foreach(File in Directory)
{
test to see if the file is a jpeg
}
但是不熟悉如何读取文件。我该怎么做呢?
最佳答案
如果您以.NET 4为目标,那么Directory.EnumerateFiles可能会更有效,尤其是对于较大的目录。如果不是,则可以用下面的EnumerateFiles
替换GetFiles
。
//add all the extensions you want to filter to this array
string[] ext = { "*.jpg", "*.jpeg", "*.jiff" };
var fPaths = ext.SelectMany(e => Directory.EnumerateFiles(myDir, e, SearchOption.AllDirectories)).ToList();
一旦有了具有正确扩展名的文件列表,就可以通过使用this answer中提到的两种不同方法中的一种来检查文件是否实际上是JPEG(而不是仅重命名为
.jpg
)。 (从该帖子)static bool HasJpegHeader(string filename)
{
using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
{
UInt16 soi = br.ReadUInt16(); // Start of Image (SOI) marker (FFD8)
UInt16 jfif = br.ReadUInt16(); // JFIF marker (FFE0)
return soi == 0xd8ff && jfif == 0xe0ff;
}
}
或更准确但更慢的方法
static bool IsJpegImage(string filename)
{
try
{
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;
}
}
如果您的JPEG文件有可能没有正确的扩展名,则必须遍历目录中的所有文件(使用
*.*
作为过滤器),并对它们执行上述两种方法之一。关于c# - 测试文件夹中的每个文件是否为jpeg,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17374508/