## 页首HTML代码 ```html

系统IO下查看bmp照片信息

IO编程

用系统IO实现查看bmp照片信息

设计程序,利用系统IO读取磁盘上指定BMP图片的宽和高,以及BMP图片的大小,并输出到终端,要求图片名称通过命令行传递。

/****************************************************************************
 *
 * file name: 2024-05-11_GetBmpInfo.c
 * author   : tongyaqi1110@163.com
 * date     : 2024-05-11
 * function : 实现在系统IO中读取一bmp图片的相关信息
 *
 * note     : None
 *
 * CopyRight (c)   2024  tongyaqi1110@163.com   All Right Reseverd
 *
 ****************************************************************************/


#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#pragma pack(1)

// 第一个结构体位图文件头结构:BITMAPFILEHEADER 的详细结构
typedef struct tagBITMAPFILEHEADER
{
  unsigned short int bfType;      // 位图文件的类型,必须为BM
  unsigned int bfSize;            // 是整个文件的大小,以字节为单位
  unsigned short int bfReserved1; // 位图保留字,必须是0
  unsigned short int bfReserved2; //  位图保留字,必须是0
  unsigned int bfOffBits;         // 是位图数据在文件中的偏移,以字节为单位
} BITMAPFILEHEADER;

// 第二个结构体位图信息头:BITMAPINFOHEADER
typedef struct tagBITMAPINFOHEADER
{
  int biSize;              // BITMAPINFOHEADER这个结构体的大小,字节为单位 必须为40(字节)
  int biWidth;             // BMP位图的宽度,以像素为单位
  int biHeight;            // BMP位图的高度,以像素为单位
  short int biPlanes;      // 目标设备的级别。这个值必须为1
  short int biBitCount;    // 颜色深度  每个像素所需要的位数
  short int biCompression; // 位图的压缩格式
  int biSizeImage;         // 位图数据块的大小。以字节为单位。如果你的位图没有经过压缩,这个值可以是0
  int biXPelsPerMeter;     // 表示横向的每米的像素数。可以为0
  int biYPelsPerMeter;     // 表示纵向的每米的像素数。可以为0
  int biClrUsed;           // 位图实际使用过的调色板的颜色数
  int biClrImportant;      // 位图显示过程中表示重要的颜色数。如果为0,表示颜色都重要。通常它的值等于biClrUsed
} BITMAPINFOHEADER;

#pragma pack()

int main(int argc, char const *argv[])
{
  // int bmp_size = 0;   // 用于存储BMP图片的大小
  // int bmp_height = 0; // 记录BMP图片的高
  // int bmp_width = 0;  // 记录BMP图片的宽

  // 1.BMP图片的路径是通过命令行传递,所以需要检测参数有效性
  if (2 != argc)
  {
    printf("argument is invaild\n");
    return -1;
  }

  // 2.利用系统调用open()打开待读取数据的BMP图片
  int bmp_fd = open(argv[1], O_RDWR);
  if (-1 == bmp_fd)
  {
    printf("open %s is error\n", argv[1]);
    return -1;
  }

  // // 3.从被打开的BMP图片中读取图像信息
  // lseek(bmp_fd, 2, SEEK_SET);
  // read(bmp_fd, &bmp_size, 4); // 读取BMP图片大小

  // lseek(bmp_fd, 18, SEEK_SET);
  // read(bmp_fd, &bmp_width, 4); // 读取BMP图片的宽

  // lseek(bmp_fd, 22, SEEK_SET);
  // read(bmp_fd, &bmp_height, 4); // 读取BMP图片的高

  struct tagBITMAPFILEHEADER s1;
  struct tagBITMAPINFOHEADER s2;

  read(bmp_fd, &s1, 14);
  read(bmp_fd, &s2, 40);
  // 4.输出BMP信息
  printf("bmp name is %s ,width = %d,height = %d,size = %d\n", argv[1], s2.biWidth, s2.biHeight, s1.bfSize);

  return 0;
}
posted @ 2024-05-11 21:31  一面小镜子  阅读(12)  评论(0编辑  收藏  举报