c语言实现对灰度图像进行上下和左右翻转
时间: 2024-02-14 11:12:19 浏览: 25
下面是使用C语言实现对灰度图像进行上下和左右翻转的示例代码:
```c
#include <stdio.h>
int main()
{
FILE *fp1, *fp2;
unsigned char header[54];
int width, height, bitCount, lineByte, i, j;
unsigned char temp;
unsigned char buffer[1024]; // 缓冲区
// 打开原始图像文件
fp1 = fopen("lena.bmp", "rb");
if (fp1 == NULL) {
printf("Failed to open file!\n");
return -1;
}
// 读取 BMP 文件头信息
fread(header, sizeof(unsigned char), 54, fp1);
width = *(int*)&header[18];
height = *(int*)&header[22];
bitCount = *(int*)&header[28];
lineByte = (width * bitCount / 8 + 3) / 4 * 4;
// 打开输出文件
fp2 = fopen("lena_flip.bmp", "wb");
if (fp2 == NULL) {
printf("Failed to create file!\n");
fclose(fp1);
return -1;
}
// 写入 BMP 文件头信息
fwrite(header, sizeof(unsigned char), 54, fp2);
// 上下翻转
for (i = height - 1; i >= 0; i--) {
fseek(fp1, 54 + i * lineByte, SEEK_SET);
fread(buffer, sizeof(unsigned char), lineByte, fp1);
fwrite(buffer, sizeof(unsigned char), lineByte, fp2);
}
// 左右翻转
fseek(fp2, 54, SEEK_SET);
for (i = 0; i < height; i++) {
for (j = 0; j < width / 2; j++) {
fseek(fp2, 54 + i * lineByte + j, SEEK_SET);
fread(&temp, sizeof(unsigned char), 1, fp2);
fseek(fp2, 54 + i * lineByte + width - j - 1, SEEK_SET);
fread(buffer, sizeof(unsigned char), 1, fp2);
fseek(fp2, 54 + i * lineByte + j, SEEK_SET);
fwrite(buffer, sizeof(unsigned char), 1, fp2);
fseek(fp2, 54 + i * lineByte + width - j - 1, SEEK_SET);
fwrite(&temp, sizeof(unsigned char), 1, fp2);
}
}
// 关闭文件
fclose(fp1);
fclose(fp2);
return 0;
}
```
注意:在运行代码之前,需要将lena.bmp文件放在代码所在的目录下,并且需要保证该文件是一个24位的BMP格式的灰度图像。