//只能处理bmp格式 24位
#include <stdio.h>
#include <stdlib.h>
//字节对齐,不然加载的数据一4字节对齐,会出现问题
#pragma pack(push)
#pragma pack(2)
//bmp分为 bmp文件头 bmp信息头 调色盘(24 32 没有) 位图数据
//一下是前两个的定义,其实Windows.h有,但我这是手机(Linux 电脑没在旁边时弄得)
//所以就从网上扒下来了
typedef unsigned short WORD;
typedef unsigned long DWORD;
typedef long LONG;
typedef struct tagBITMAPFILEHEADER {
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} BITMAPFILEHEADER;
typedef struct tagBITMAPINFOHEADER{
DWORD biSize;
LONG biWidth;
LONG biHeight;
WORD biPlanes;
WORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
LONG biXPelsPerMeter;
LONG biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} BITMAPINFOHEADER;
#pragma pack(pop)
int main(){
//图像的地址
char strFile[260] = "黄鹤楼.bmp";
char strBuf[260];
FILE* fp = fopen(strFile,"rb");
if(fp == NULL) {
printf("打开文件失败...\n");
return -1;
}
//保存图像地址
FILE *fSava = fopen("灰度化.bmp","wb");
BITMAPFILEHEADER bmpFileHead;
BITMAPINFOHEADER bmpInfoHead;
fread(&bmpFileHead,sizeof(BITMAPFILEHEADER ),1,fp);
fread(&bmpInfoHead,sizeof( BITMAPINFOHEADER),1,fp);
//BMP以BM开头 位数是不是24位
if(bmpFileHead.bfType != 19978 || bmpInfoHead.biBitCount!=24){
printf("这啥图片,不合格\n");
getchar();
return -1;
}
printf("图片大小为:%dbyte\n分辨率:%d * %d\nbmp数据偏移:%dbyte\n",bmpFileHead.bfSize\
,bmpInfoHead.biWidth,bmpInfoHead.biHeight , bmpFileHead.bfOffBits );
int size = bmpFileHead.bfSize - bmpFileHead.bfOffBits;
fwrite(&bmpFileHead,sizeof(bmpFileHead),1,fSava);
fwrite(&bmpInfoHead,sizeof(bmpInfoHead),1,fSava);
for(int i = 0; i < size; i+=3){
char color[3];
fread(color,1,3,fp);
char buf = (color[0] + color[1] +color[2])/3; //灰度化 需要bmp格式 24位 32位多了个A
for(int j = 0; j < 3; j++){
fwrite(&buf,1,1,fSava);
}
}
fclose(fSava);
fclose(fp);
printf("写入完成!\n");
getchar();
return 0;
}