2

I want to check if images in a directory are of type png but with extension .bmp. The following determines whether it is a .bmp extension

 string x = Path.GetExtension(file);

From this we establish that its extension is .bmp. Now the problem comes in checking if it is in a png format. I am stuck on this part.

The reason why I am doing this is because I want to have my images transparent and .bmp images don't work so well with that. Thank you!

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
haysam
  • 401
  • 5
  • 11
  • 16
  • 2
    See the accepted answer and first comment: http://stackoverflow.com/questions/670546/determine-if-file-is-an-image – George Johnston Jun 03 '13 at 20:24
  • @GeorgeJohnston Even if the file is with an extension .bmp, the last 8 bits will be that answer that is in the other post? Interesting – haysam Jun 03 '13 at 20:27
  • @haysam the first 8 bytes, not the last 8 bits, but yes - the extension is just part of the filename, it's just convention that bitmaps are '.bmp' and PNGs are '.png' – Blorgbeard Jun 03 '13 at 20:29

4 Answers4

11

The above answer is incorrect, the code should be:

var header = new byte[4];
using (var fs = new FileStream(filename))
{
    fs.Read(header, 0, 4);
}

var strHeader = Encoding.ASCII.GetString(header);
return strHeader.ToLower().EndsWith("png");
Andrew dh
  • 881
  • 9
  • 19
0

We can check the file extension with this

 Byte[] imageBase64 = ....

 var encodedFile = Encoding.ASCII.GetString(imageBase64);
 return encodedFile.ToLower().StartsWith("?png", StringComparison.InvariantCultureIgnoreCase);
Manni Dula
  • 49
  • 4
0

Here is another take that I personally like since you don't have to check against strings (using the System.Drawing Library).

using (var fs = new FileStream(filename))
{
    var fsImage = System.Drawing.Image.FromStream(fs);
    if (fsImage.RawFormat == System.Drawing.Imaging.ImageFormat.Jpeg)
    {
       // Do something with Jpegs
    }
    else if (fsImage.RawFormat == System.Drawing.Imaging.ImageFormat.Png)
    {
       // Do something with Pngs
    }
}
William
  • 3,335
  • 9
  • 42
  • 74
-1

Read the first 4 bytes of the file:

byte[] b = new byte[4];
using (var fs = new FileStream(filename))
{
    fs.Read(b, 0, 4);
}
if (b.ToString().Contains("PNG"))
{
    // this is a png file
}
klugerama
  • 3,312
  • 19
  • 25
  • Yes, you can't always trust the filename extension. You should *always* check the file signature (first few magic bytes) to make sure the file is actually the type it claims to be. – David R Tribble Jun 03 '13 at 23:56
  • -1 this is incorrect - answr below by @Andrew dh works – lstanczyk Jun 26 '14 at 17:51