【C#】获取图像(jpeg/jpg/png/gif/bmp/tiff)的正确格式 - 二进制头判断
|
admin
2025年4月17日 20:57
本文热度 14
|
前言
在学习Halcon的过程中,遇到了一些问题,就是读取图像后缀明明是png格式的,路径也是正确的,但是读取时图像就是报错,这是为什么呢?
经过一番检查发现,是不小心修改了图像后缀名导致的报错,那么该如何判断图像的正确格式呢,其实每种图像格式都有其独特的二进制头部标识,通过读取图像的二进制头就可以判断图像的正确格式。
下面我们将介绍如何使用 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
优点:准确可靠,确保文件头与图像格式匹配。
缺点:需要解析文件内容,稍微占用资源。
运行环境
操作系统: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 编辑过