C# How can I test a file is a jpeg?

后端 未结 16 2332
失恋的感觉
失恋的感觉 2020-11-27 03:28

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

Thanks

相关标签:
16条回答
  • 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 number in 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;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 03:57

    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.

    0 讨论(0)
  • 2020-11-27 03:58

    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.FromFile(@"c:\temp\test.jpg");
    

    This isn't ideal as you could get any kind of exception, such as OutOfMemoryException, FileNotFoundException, etc. etc.

    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.

    0 讨论(0)
  • 2020-11-27 03:58

    Just take the media type of file and verify:

    private bool isJpeg()
            {
    string p = currFile.Headers.ContentType.MediaType;
                return p.ToLower().Equals("image/jpeg") || p.ToLower().Equals("image/pjpeg") || p.ToLower().Equals("image/png");
            }
    
    0 讨论(0)
提交回复
热议问题