zoukankan      html  css  js  c++  java
  • 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;
                }
            }
    
  • 相关阅读:
    序列
    2018131
    成都七中
    NOIP2017
    洛谷P1352 CodeVS1380 没有上司的舞会
    BZOJ1087 SCOI2005 互不侵犯King
    11-4-2017 星期六 R-Day?
    11-3-2017 星期五
    11-2-2017 星期四
    USACO 2014 US Open, Silver Problem 2. Dueling GPSs
  • 原文地址:https://www.cnblogs.com/zuixime0515/p/12930090.html
Copyright © 2011-2022 走看看