前言
在學習Halcon的過程中,遇到了一些問題,就是讀取圖像后綴明明是png格式的,路徑也是正確的,但是讀取時圖像就是報錯,這是為什么呢?
經過一番檢查發(fā)現(xiàn),是不小心修改了圖像后綴名導致的報錯,那么該如何判斷圖像的正確格式呢,其實每種圖像格式都有其獨特的二進制頭部標識,通過讀取圖像的二進制頭就可以判斷圖像的正確格式。
下面我們將介紹如何使用 C# 讀取圖像的二進制頭標識判圖像文件的正確格式。
幾種常用的圖像頭部標識:
JPEG: 0xFF, 0xD8
PNG: 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A
GIF: 0x47, 0x49, 0x46
BMP: 0x42, 0x4D
TIFF: 0x49, 0x49, 0x2A, 0x00 或 0x4D, 0x4D, 0x00, 0x2A
優(yōu)點:準確可靠,確保文件頭與圖像格式匹配。
缺點:需要解析文件內容,稍微占用資源。
運行環(huán)境
操作系統(tǒng):Window 11
編程軟件:Visual Studio 2022
.Net版本:.Net Framework 4.6
代碼
#region 判斷圖像的正確格式
public static ImageFormat GetImageFormat(string filePath)
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] headerBytes = br.ReadBytes(16);
if (IsJpeg(headerBytes))
{
return ImageFormat.Jpeg;
}
else if (IsPng(headerBytes))
{
return ImageFormat.Png;
}
else if (IsGif(headerBytes))
{
return ImageFormat.Gif;
}
else if (IsBmp(headerBytes))
{
return ImageFormat.Bmp;
}
else
{
return null;
}
}
}
}
private static bool IsJpeg(byte[] headerBytes)
{
return headerBytes.Length >= 2 && headerBytes[0] == 0xFF && headerBytes[1] == 0xD8;
}
private static bool IsPng(byte[] headerBytes)
{
return headerBytes.Length >= 8 && headerBytes[0] == 137
&& headerBytes[1] == 80 && headerBytes[2] == 78
&& headerBytes[3] == 71 && headerBytes[4] == 13
&& headerBytes[5] == 10 && headerBytes[6] == 26
&& headerBytes[7] == 10;
}
private static bool IsGif(byte[] headerBytes)
{
return headerBytes.Length >= 3 && headerBytes[0] == 71
&& headerBytes[1] == 73 && headerBytes[2] == 70;
}
private static bool IsBmp(byte[] headerBytes)
{
return headerBytes.Length >= 2 && headerBytes[0] == 66
&& headerBytes[1] == 77;
}
#endregion
該文章在 2025/4/19 10:11:55 編輯過