C语言中使用文件处理函数修改.bmp格式图片的颜色代码

#include<stdio.h>
int main()
{
FILE *fp,*fp1;
fp=fopen("/Users/lanou/Desktop/1.bmp","rb");
fp1=fopen("/Users/lanou/Desktop/6.bmp","wb");
char content,head[54];
unsigned char wrt;
unsigned int no=1;
unsigned char r=0,b=0,g=0;
int no_avg=1;
fread(head,1,54,fp);
fwrite(head,1,54,fp1);
unsigned size = *(unsigned*)(head+2);
size=size-54;
size /= 3;
while(size--)
{
b = getc(fp);
g = getc(fp);
r = getc(fp);
wrt = (b+g+r)/3;
putc(wrt,fp1);
putc(wrt,fp1);
putc(wrt,fp1);
}

printf("OK");

fclose(fp);
fclose(fp1);
}

转载于:https://www.cnblogs.com/yuanyuandachao/p/3342944.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的 C 语言示例程序,用于从 BMP 文件读取图像数据: ```c #include <stdio.h> #include <stdlib.h> #include <stdint.h> #pragma pack(push, 1) typedef struct { uint16_t type; uint32_t size; uint16_t reserved1; uint16_t reserved2; uint32_t offset; } bmp_file_header_t; typedef struct { uint32_t size; int32_t width; int32_t height; uint16_t planes; uint16_t bit_count; uint32_t compression; uint32_t size_image; int32_t x_pels_per_meter; int32_t y_pels_per_meter; uint32_t clr_used; uint32_t clr_important; } bmp_info_header_t; #pragma pack(pop) int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: %s input.bmp\n", argv[0]); return 0; } FILE *input_file = fopen(argv[1], "rb"); if (!input_file) { printf("Failed to open input file: %s\n", argv[1]); return 0; } bmp_file_header_t file_header; bmp_info_header_t info_header; fread(&file_header, sizeof(bmp_file_header_t), 1, input_file); fread(&info_header, sizeof(bmp_info_header_t), 1, input_file); if (file_header.type != 0x4d42 || info_header.bit_count != 24 || info_header.compression != 0) { printf("Invalid input file format.\n"); fclose(input_file); return 0; } uint32_t width = abs(info_header.width); uint32_t height = abs(info_header.height); uint32_t line_size = (width * 3 + 3) & ~3; uint8_t *image_data = (uint8_t *)malloc(line_size * height); fseek(input_file, file_header.offset, SEEK_SET); fread(image_data, line_size, height, input_file); fclose(input_file); // 现在 image_data 存储了 BMP 文件的像素数据,可以进行进一步处理 free(image_data); printf("Done.\n"); return 0; } ``` 在这个示例代码,我们使用了两个结构体来解析 BMP 文件头和信息头的数据。首先,我们打开 BMP 文件并读取文件头和信息头。然后,我们检查文件头和信息头是否符合要求(即文件类型必须是 "BM",颜色位数必须是 24 位,不支持压缩)。接下来,我们计算每一行像素数据的字节数,使用 malloc 函数分配足够的内存来存储像素数据,并使用 fread 函数从文件读取像素数据。最后,我们关闭文件,并使用 free 函数释放内存。 请注意,这个示例代码只适用于 24 位彩色 BMP 图片。如果你想处理其他格式BMP 图片,需要根据实际情况进行修改

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值