尝试使用 BMP 图像。在逐字节写入图片本身的值之前,我决定先以二进制形式写入标题,无论我为init
结构中的变量选择什么数据类型BMP_header
- 变量都遇到了这样的问题反正valuesinit
都是4字节写的。
这是BMP图像的结构global.h
typedef struct {
short int init;
int file_size;
int unusable_values;
int header_size
} BMP_header;
typedef struct {
int dib_header_size;
int width;
int height;
short int color_plane
short int bits_per_pixel;
int compression;
int image_contents_size;
int horisontal_resolution;
int vertical_resolution;
int unusable_var1;
int unusable_var2;
} DIB_header;
typedef struct {
BMP_header bmp_header;
DIB_header dib_header;
} BMP;
这是我用来编写文件的代码
#include <stdio.h>
#include <stdlib.h>
#include "Manipulation/Global/headers/global.h"
void image(int width, int height, int values_array[]);
int main(void) {
int color = 0x00ffffff;
int height = 4;
int width = 4;
int values_array[width * height];
for(int i = 0; i < width * height; i++)
values_array[i] = color;
image(width, height, values_array);
}
void image(int width, int height, int values_array[]) {
BMP image = {
0x4d42,
(width * height * 4) + 54,
0x00000000,
0x00000036,
0x00000028,
width,
height,
0x0001,
0x0018,
0x00000000,
width * height * 4,
0x00000ec4,
0x00000ec4,
0x00000000,
0x00000000
};
BMP *p_image = ℑ
FILE *fp;
if((fp = fopen("image.bmp", "w")) == NULL) {
perror("Ошибка создания файла\n");
exit(0);
}
fwrite(p_image, sizeof(image), 1, fp);
fclose(fp);
}
这是我最终得到的
42 4D 00 00 76 00 00 00 00 00 00 00 36 00 00 00
28 00 00 00 04 00 00 00 04 00 00 00 01 00 18 00
00 00 00 00 40 00 00 00 C4 0E 00 00 C4 0E 00 00
00 00 00 00 00 00 00 00
这就是我期望得到的
42 4D 76 00 00 00 00 00 00 00 36 00 00 00 28 00
00 00 04 00 00 00 04 00 00 00 01 00 18 00 00 00
00 00 40 00 00 00 C4 0E 00 00 C4 0E 00 00 00 00
00 00 00 00 00 00
问题:为什么无论变量的类型如何,后面的最开始都多了42 4D
2个字节?00 00
init
我没有仔细研究代码,但我认为这是由于字段对齐所致。
或者,您可以打包结构,使其中没有“孔”。如何?例如,在 gcc 中:
pragma pack 还有一个更便携的版本,你可以自己熟悉一下。