C#根据二进制头判断图像格式

既是分享也是保存。

C#根据二进制头判断图像格式

代码

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值