#include <stdio.h>
#include <malloc.h>
#define path '添加你的图片路径'
#define BM 19778
typdef struct functions
{
int IsBitMap(FILE *fp);//判断是否是bmp图片
long getWidth(FILE *fp);//获取图像的宽
long getHeight(FILE *fp);//获取图像的高
unsigned short getBit(FILE *fp);//获得每个像素的位数
unsigned int getOffSet(FILE *fp);//获得数据的起始位置,即数据偏移量
void getData(FILE* fp, unsigned char *r, unsigned char *g, unsigned char *b)//获取图片的DIB数据
}
int IsBitMap(FILE *fp)//判断是否是bmp图片
{
FILE *fp=fopen(path,'rb');
unsign short s;
fread(&s,1,2,fp);
if(s==BM) return 1;
else
return 0;
}
//获得图片的宽度,在18-21字节
long getWidth(FILE *fp)
{
long width;
fseek(fp, 18, SEEK_SET);
fread(&width, 1, 4, fp);
return width;
}
//获得图片的高度 ,在22-25字节
long getHeight(FILE *fp)
{
long height;
fseek(fp, 22, SEEK_SET);
fread(&height, 1, 4, fp);
return height;
}
//获得每个像素的位数,在28-29字节
unsigned short getBit(FILE *fp)
{
unsigned short bit;
fseek(fp, 28, SEEK_SET);
fread(&bit, 1, 2, fp);
return bit;
}
//获得数据的起始位置
unsigned int getOffSet(FILE *fp)
{
unsigned int OffSet;
fseek(fp, 10L, SEEK_SET);
fread(&OffSet, 1, 4, fp);
return OffSet;
}
//获得三通道的数组
void getData(FILE* fp, unsigned char *r, unsigned char *g, unsigned char *b)
{
FILE* fpr;
FILE* fpg;
FILE* fpb;
int i, j = 0;
int stride;
unsigned char* pix = NULL;
long height, width;
height = getHeight(fp);
width = getWidth(fp);
fseek(fp, getOffSet(fp), SEEK_SET); //找到位图的数据区
stride = (24 * width + 31) / 8; //对齐,计算一个width有多少个8位
stride = stride / 4 * 4; //取四的倍数 r,g,b,alph
//写入数组
pix = (unsigned char *)malloc(stride*height);
fpr = fopen("d:\\bmpr.txt", "w+");
fpg = fopen("d:\\bmpg.txt", "w+");
fpb = fopen("d:\\bmpb.txt", "w+");
fread(pix, 1, stride*height, fp);
for (j = 0; j<height; j++)
{
for (i = 0; i<width; i++)
{
fprintf(fpr, "%4d", pix[((height - j - 1)* width + i) * 3 + 2]);
fprintf(fpg, "%4d", pix[((height - j - 1)* width + i) * 3 + 1]);
fprintf(fpb, "%4d", pix[((height - j - 1)* width + i) * 3]);
}
fprintf(fpr, "\n");
fprintf(fpg, "\n");
fprintf(fpb, "\n");
}
//写入文件
fclose(fpr);
fclose(fpg);
fclose(fpb);
}
int main()
{
long width, height;
FILE *fp = fopen(PATH, "r");
unsigned char *r, *g, *b;
int i, j;
r = (unsigned char *)malloc(8000);
b = (unsigned char *)malloc(8000);
g = (unsigned char *)malloc(8000);
if (IsBitMap(fp))
printf("该文件是位图!\n");
else
{
printf("该文件不是位图!\n");
fclose(fp);
return 0;
}
printf("width=%ld\nheight=%ld\n", getWidth(fp), getHeight(fp));
printf("该图像是%d位图\n", getBit(fp));
printf("OffSet=%d\n", getOffSet(fp));
getData(fp, r, g, b);
return (0);
}
2.1 图像处理框架搭建一之图像的输入输出
最新推荐文章于 2022-01-19 20:01:06 发布