Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Several options:</p> <p>You can check for the file extension:</p> <pre><code>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); } </code></pre> <p>or check for the correct <a href="https://web.archive.org/web/20100212180433/http://www.obrador.com/essentialjpeg/headerinfo.htm" rel="nofollow noreferrer">magic number</a> in the header of the file:</p> <pre><code>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(FF01) return soi == 0xd8ff &amp;&amp; (marker &amp; 0xe0ff) == 0xe0ff; } } </code></pre> <p>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):</p> <pre><code>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; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload