LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

【C#】获取图像(jpeg/jpg/png/gif/bmp/tiff)的正确格式 - 二进制头判断

admin
2025年4月17日 20:57 本文热度 14
    

本文描述C#如何使用二进制头判断图像的正确格式。

前言 



在学习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 判断图像的正确格式/// <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


该文章在 2025/4/19 10:11:55 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved