背景
最近自己在做一個功能的時候,需要判斷一個文件是否是真的圖片,也就是說類似通過修改后綴名的方法偽造的圖片需要識別出來。拿到這個功能的時候,自己首先想到的是C#是否有相關的類可以判斷是否是圖片,例如通過給出文件路徑,用相關的方法是否可以構造出一個image對象;如果沒有對應的方法的話,那么自己只能通過文件的內容格式來進行判斷,也就是說自己通過讀取文件的內容,用相關的數據做判斷;
代碼實現
- 通過通過Image類的相關方法構建一個對象,如果是真的圖片,那么可以構建對象成功,否則失敗;
public static bool IsRealImage(string path)
{
try
{
Image img = Image.FromFile(path);
Console.WriteLine("\nIt is a real image");
return true;
}
catch (Exception e)
{
Console.WriteLine("\nIt is a fate image");
return false;
}
}
- 通過文件內容來進行判斷,在這里我只判斷是否是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("\nIt is a real jpg or png files");
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
return false;
}
}