C#如何测试一个文件是一个JPEG? [英] C# How can I test a file is a jpeg?

查看:176
本文介绍了C#如何测试一个文件是一个JPEG?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#我怎么能测试一个文件是一个JPEG?我应该检查.jpg扩展名?

Using C# how can I test a file is a jpeg? Should I check for a .jpg extension?

感谢

推荐答案

有几个选项:

您可以检查文件的扩展名:

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);
}

或检查正确幻数在文件头的:

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 marker = br.ReadUInt16(); // JFIF marker (FFE0) or EXIF marker(FF01)

        return soi == 0xd8ff && (marker & 0xe0ff) == 0xe0ff;
    }
}

另一种选择是加载图像并检查正确的类型。然而,这是效率不高(除非你打算无论如何要加载图像),但可能会为您提供最可靠的结果(请注意加载和DECOM pression的额外费用,以及可能的异常处理):

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
    {
        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;
    }
}

这篇关于C#如何测试一个文件是一个JPEG?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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