- 摘要 : C# 读取文件的二进制头实现图像格式正确判断。
-
前言
- 在 C# 中,可以通过读取文件的二进制头(Magic Number)来判断图像格式。
- 每种图像格式都有其独特的二进制头部标识。
- 根据读取文件的前几个字节并与这些标识进行匹配,可以准确地判断文件类型。
- 通过这种方法,可以高效地判断图像文件的格式。
-
常见图像格式的二进制头:
- 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
-
优缺点
- 优点:准确可靠,确保文件头与图像格式匹配。
- 缺点:需要解析文件内容,稍微占用资源。
-
主要功能
- 核心方法 GetImageFormat(string filePath):。
- 输入文件路径,返回对应的ImageFormat枚举值。
- 支持JPEG、PNG、GIF和BMP四种常见图像格式的判断。
- 对于无法识别的格式返回null。
-
代码
#region 判断图像的正确格式 /// <summary> /// 图像格式工具:获取正确的图像格式,通过图像文件的二进制头部图像格式标识。 /// </summary> 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) { // JPEG 文件的前两个字节是 0xFF, 0xD8 return headerBytes.Length >= 2 && headerBytes[0] == 0xFF && headerBytes[1] == 0xD8; } private static bool IsPng(byte[] headerBytes) { // PNG 文件的前八个字节是固定的签名:137 80 78 71 13 10 26 10 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) { // GIF 文件的前三个字节是 "GIF" return headerBytes.Length >= 3 && headerBytes[0] == 71 && headerBytes[1] == 73 && headerBytes[2] == 70; } private static bool IsBmp(byte[] headerBytes) { // BMP 文件的前两个字节是 "BM" return headerBytes.Length >= 2 && headerBytes[0] == 66 && headerBytes[1] == 77; } #endregion
-
结语
- 示例代码适用于需要准确判断图像实际格式的应用程序,文件扩展名不可信时的格式验证,图像处理工具中确保输入文件的正确性。
- 使用using语句确保FileStream和BinaryReader正确释放,避免资源泄漏。
- 添加了异常检查功能,每次执行先验证字节数组长度防止数组越界异常。
- 代码结构清晰,易于添加对其他图像格式的支持,只需添加新的判断方法并在主方法中添加条件分支。