C#中如何判断文件是否是图片

背景

最近自己在做一个功能的时候,需要判断一个文件是否是真的图片,也就是说类似通过修改后缀名的方法伪造的图片需要识别出来。拿到这个功能的时候,自己首先想到的是C#是否有相关的类可以判断是否是图片,例如通过给出文件路径,用相关的方法是否可以构造出一个image对象;如果没有对应的方法的话,那么自己只能通过文件的内容格式来进行判断,也就是说自己通过读取文件的内容,用相关的数据做判断;

代码实现

  1. 通过通过Image类的相关方法构建一个对象,如果是真的图片,那么可以构建对象成功,否则失败;
public static bool IsRealImage(string path)
        {
            try
            {
                Image img = Image.FromFile(path);
                Console.WriteLine("
It is a real image");
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine("
It is a fate image");
                return false;
            }
        }
  1. 通过文件内容来进行判断,在这里我只判断是否是JPG和PNF文件,其他格式的图片的类似
public static bool JudgeIsRealSpecialImage(string path)
        {
            try
            {
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                BinaryReader reader = new BinaryReader(fs);
                string fileType;
                byte buffer;

                buffer = reader.ReadByte();
                fileType = buffer.ToString();
                buffer = reader.ReadByte();
                fileType += buffer.ToString();

                reader.Close();
                fs.Close();

                if (fileType == "13780" || fileType == "255216")
                {
                    Console.WriteLine("
It is a real jpg or png files");
                    return true;
                }
                else
                {
                    return false; 
                }
            }
            catch (Exception e)
            {
                return false;
            }
        }
原文地址:https://www.cnblogs.com/zuixime0515/p/12930090.html