bmp图片生成及像素修改的源码
Gitee源码地址
CSDN阅读地址
- 简介:使用Qt、Gcc(可以是Linux或者MinGW等)编译环境,使用C语言编写。自行生成并保存BMP文件,修改BMP文件中像素。
一、BMP概述
二、编译及使用
- 在tag为v1.0.0的软件源码下:
- 如果是在32位Linux系统下,或者Linux系统里已经配置了32位的GCC,或者Windows中的MinGW已经安装了32位的GCC,则直接使用命令 gcc -o demo main.c
- 编译完成了会生成名为demo,或者名为demo.exe的文件,直接 ./demo 运行或者双击运行,会在源码同级目录下生成picture.bmp文件,直接双击打开这个bmp文件,会看到是一张1280x720的灰色图片。
- 警告:当前版本源码在64位编译环境下生成的图片在逻辑上一定不对,我并没有也没必要在这种编译环境测试代码。
三、源码内容
#include <string.h>
#include <stdio.h>
typedef struct _bitmap_file_header {
short int type;
int size;
short int rsv1;
short int rsv2;
int off_bits;
} __attribute__ ((packed)) BITMAP_FILE_HEADER_T;
typedef struct _bitmap_info_header {
int size;
int width;
int height;
short int planes;
short int bit_count;
int compression;
int size_image;
int x_pels_per_meter;
int y_pels_per_meter;
int clr_used;
int clr_important;
} __attribute__ ((packed)) BITMAP_INFO_HEADER_T;
typedef struct _rgb_quad {
char rgb_blue;
char rgb_green;
char rgb_red;
char rgb_rsv;
} __attribute__ ((packed)) RGB_QUAD_T;
#define WIDTH 1280
#define HEIGHT 720
#define BIT_DEPTH 3
char image_data[(WIDTH + 4) * HEIGHT * BIT_DEPTH];
int main()
{
int bit_depth = BIT_DEPTH * 8;
int width = WIDTH;
int height = HEIGHT;
int info_header_size = sizeof(BITMAP_INFO_HEADER_T);
char *file_name = "picture.bmp";
BITMAP_FILE_HEADER_T file_header;
memset(&file_header, 0, sizeof(file_header));
file_header.type = ('M' << 8) | 'B';
BITMAP_INFO_HEADER_T info_header;
memset(&info_header, 0, sizeof(info_header));
info_header.size = info_header_size;
info_header.width = width;
info_header.height = height;
info_header.planes = 1;
info_header.bit_count = bit_depth;
info_header.compression = 0;
info_header.size_image =
((width % 4) ? ((width / 4) * 4 + 4) : width) * height;
info_header.x_pels_per_meter = 2800;
info_header.y_pels_per_meter = 2800;
if (info_header.bit_count >= 24) {
file_header.size = sizeof(file_header) + sizeof(info_header)
+ info_header.size_image * info_header.bit_count / 8;
file_header.off_bits = sizeof(file_header) + sizeof(info_header);
} else {
printf("bit depth %d not support!\n", info_header.bit_count);
return 0;
}
FILE *fp = fopen(file_name, "wb+");
if (fp == NULL) {
printf("create file %s fail!\n", file_name);
return 0;
}
int image_length = info_header.size_image * info_header.bit_count / 8;
for (int i = 0; i < image_length; i++) {
image_data[i] = 0x7F;
}
fwrite(&file_header, 1, sizeof(file_header), fp);
fwrite(&info_header, 1, sizeof(info_header), fp);
if (info_header.bit_count < 24) {
printf("err: please add codes parse bit count %d\n", info_header.bit_count);
}
fwrite(image_data, image_length, 1, fp);
fflush(fp);
fclose(fp);
return 0;
}