BMP位图文件头和信息头的使用
这里给文件头和信息头设置了两个结构图来存储信息
/*************************************************************************
* file name:bmpuse
* function: 输入bmp图片,输出图片文件的宽高和文件大小信息
* date: 2025.5.21
* note:需要在执行文件时 写入所计算图片的名字
* 例:
* ./main a.bmp
* Copyright (c) 2024-2025 l550036303@163.com All right reserved
**************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#pragma pack(1) //取消字节对齐
struct bmp_head { //文件头
char type[2];//位图文件的类型,必须为BM(1-2字节)
int size; //位图文件的大小,以字节为单位(3-6字节,低位在前)
short reserved1;//位图文件保留字,必须为0(7-8字节)
short reserved2;//位图文件保留字,必须为0(9-10字节)
int offbits; //位图数据的起始位置,以相对于位图(11-14字节,低位在前),文件头的偏移量表示,以字节为单位
};
struct bmp_info { // 信息头
int infosize; //本结构所占用字节数(15-18字节)
int width; //位图的宽度,以像素为单位(19-22字节)
int height; //位图的高度,以像素为单位(23-26字节)
short planes; //目标设备的级别,必须为1(27-28字节)
short bit_count; //每个像素所需的位数,必须是1(双色),(29-30字节)//4(16色),8(256色)16(高彩色)或24(真彩色)之一
int compression;//位图压缩类型,必须是0(不压缩),(31-34字节) //1(BI_RLE8压缩类型)或2(BI_RLE4压缩类型)之一
int size_img; //位图的大小(其中包含了为了补齐列数是4的倍数而添加的空字节),以字节为单位(35-38字节)
int X_pel; //位图水平分辨率,每米像素数(39-42字节)
int Y_pel; //位图垂直分辨率,每米像素数(43-46字节)
int clrused; //位图实际使用的颜色表中的颜色数(47-50字节)
int clrImportant; //位图显示过程中重要的颜色数(51-54字节)
};
#pragma pack() //恢复字节对齐
void main(int argc,char const *argv[]){
if(2 != argc){
perror("this argument invalid");
exit(-1); //stdlib.h
}
#if 0
int width=0;
int height=0;
int size=0;
int bmp_fd =open(argv[1],O_RDWR);
lseek(bmp_fd,18,SEEK_SET);
read(bmp_fd,&width,4);
lseek(bmp_fd,22,SEEK_SET);
read(bmp_fd,&height,4);
lseek(bmp_fd,2,SEEK_SET);
read(bmp_fd,&size,4);
printf("size=%d\theight=%d\twidth=%d\n",size,height,width);
#endif
#if 1
int bmp_fd =open(argv[1],O_RDWR);
struct bmp_head bmphead;
struct bmp_info bmpinfo;
read(bmp_fd,&bmphead,14);
read(bmp_fd,&bmpinfo,40);
printf("size=%d\theight=%d\twidth=%d\n",bmphead.size,bmpinfo.height,bmpinfo.width);
#endif
}

浙公网安备 33010602011771号