C语言实现BMP图像灰度化:fread()、fwrite()函数应用
#include <stdio.h> #include <stdlib.h>
#pragma pack(2) // 设置结构体按2字节对齐
typedef struct { char bfType[2]; // 位图文件类型,必须为'BM' int bfSize; // 位图文件大小 short bfReserved1; // 保留字节 short bfReserved2; // 保留字节 int bfOffBits; // 从文件头到实际位图数据的偏移字节数 } BMPFILEHEADER;
typedef struct { int biSize; // 位图信息头大小 int biWidth; // 位图宽度 int biHeight; // 位图高度 short biPlanes; // 颜色平面数,必须为1 short biBitCount; // 每个像素的位数 int biCompression; // 压缩类型 int biSizeImage; // 图像大小 int biXPelsPerMeter; // 水平分辨率 int biYPelsPerMeter; // 垂直分辨率 int biClrUsed; // 颜色索引数 int biClrImportant; // 重要颜色索引数 } BMPINFOHEADER;
typedef struct { unsigned char b; unsigned char g; unsigned char r; } RGB;
int main() { BMPFILEHEADER fileHeader; BMPINFOHEADER infoHeader; RGB **image; RGB **grayImage; FILE *fpIn, *fpOut; int i, j;
// 打开原始图像文件
fpIn = fopen('1.bmp', 'rb');
if (fpIn == NULL) {
printf('Failed to open file 1.bmp\n');
return 1;
}
// 读取文件头信息
fread(&fileHeader, sizeof(BMPFILEHEADER), 1, fpIn);
if (fileHeader.bfType[0] != 'B' || fileHeader.bfType[1] != 'M') {
printf('Invalid BMP file\n');
return 1;
}
// 读取图像信息头
fread(&infoHeader, sizeof(BMPINFOHEADER), 1, fpIn);
if (infoHeader.biBitCount != 24) {
printf('Only support 24-bit BMP file\n');
return 1;
}
// 分配内存存储原始图像数据
image = (RGB **)malloc(sizeof(RGB *) * infoHeader.biHeight);
for (i = 0; i < infoHeader.biHeight; i++) {
image[i] = (RGB *)malloc(sizeof(RGB) * infoHeader.biWidth);
}
// 读取原始图像数据
for (i = 0; i < infoHeader.biHeight; i++) {
for (j = 0; j < infoHeader.biWidth; j++) {
fread(&image[i][j], sizeof(RGB), 1, fpIn);
}
}
// 关闭原始图像文件
fclose(fpIn);
// 分配内存存储灰度图像数据
grayImage = (RGB **)malloc(sizeof(RGB *) * infoHeader.biHeight);
for (i = 0; i < infoHeader.biHeight; i++) {
grayImage[i] = (RGB *)malloc(sizeof(RGB) * infoHeader.biWidth);
}
// 转换为灰度图像
for (i = 0; i < infoHeader.biHeight; i++) {
for (j = 0; j < infoHeader.biWidth; j++) {
int gray = (image[i][j].r + image[i][j].g + image[i][j].b) / 3;
grayImage[i][j].r = gray;
grayImage[i][j].g = gray;
grayImage[i][j].b = gray;
}
}
// 打开输出图像文件
fpOut = fopen('2.bmp', 'wb');
if (fpOut == NULL) {
printf('Failed to open file 2.bmp\n');
return 1;
}
// 写入文件头信息
fwrite(&fileHeader, sizeof(BMPFILEHEADER), 1, fpOut);
fwrite(&infoHeader, sizeof(BMPINFOHEADER), 1, fpOut);
// 写入灰度图像数据
for (i = 0; i < infoHeader.biHeight; i++) {
for (j = 0; j < infoHeader.biWidth; j++) {
fwrite(&grayImage[i][j], sizeof(RGB), 1, fpOut);
}
}
// 关闭输出图像文件
fclose(fpOut);
// 释放内存
for (i = 0; i < infoHeader.biHeight; i++) {
free(image[i]);
free(grayImage[i]);
}
free(image);
free(grayImage);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/jCZr 著作权归作者所有。请勿转载和采集!