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

后端 未结 16 2331
失恋的感觉
失恋的感觉 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条回答
  • 2020-11-27 03:45

    The code here:

    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.

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

    Depending on the context in which you're looking at this file, you need to remember that you can't open the file until the user tells you to open it.

    (The link is to a Raymond Chen blog entry.)

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

    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.

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

    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

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

    Read the header bytes. This article contains info on several common image formats, including JPEG:

    Using Image File Headers To Verify Image Format

    JPEG Header Information

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

    You can use the Path.GetExtension Method.

    0 讨论(0)
提交回复
热议问题