生成bmp文件C语言代码
时间: 2023-12-10 11:03:44 浏览: 33
以下是一个简单的生成 BMP 文件的 C 语言代码,它可以生成一个 24 位色的 BMP 文件。
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma pack(push, 1)
typedef struct {
unsigned char signature[2];
unsigned int size;
unsigned int reserved;
unsigned int offset;
} BMPHeader;
typedef struct {
unsigned int size;
int width;
int height;
unsigned short planes;
unsigned short bitsPerPixel;
unsigned int compression;
unsigned int imageSize;
int xResolution;
int yResolution;
unsigned int colorsUsed;
unsigned int importantColors;
} BMPInfoHeader;
#pragma pack(pop)
void writeBMP(char* filename, unsigned char* data, int width, int height) {
BMPHeader header;
BMPInfoHeader infoHeader;
FILE* file = fopen(filename, "wb");
int rowSize = (width * 3 + 3) & ~3;
int pixelArraySize = rowSize * height;
header.signature[0] = 'B';
header.signature[1] = 'M';
header.size = sizeof(BMPHeader) + sizeof(BMPInfoHeader) + pixelArraySize;
header.reserved = 0;
header.offset = sizeof(BMPHeader) + sizeof(BMPInfoHeader);
infoHeader.size = sizeof(BMPInfoHeader);
infoHeader.width = width;
infoHeader.height = height;
infoHeader.planes = 1;
infoHeader.bitsPerPixel = 24;
infoHeader.compression = 0;
infoHeader.imageSize = pixelArraySize;
infoHeader.xResolution = 0;
infoHeader.yResolution = 0;
infoHeader.colorsUsed = 0;
infoHeader.importantColors = 0;
fwrite(&header, sizeof(header), 1, file);
fwrite(&infoHeader, sizeof(infoHeader), 1, file);
for (int y = height - 1; y >= 0; y--) {
int rowOffset = y * width * 3;
for (int x = 0; x < width; x++) {
int pixelOffset = rowOffset + x * 3;
unsigned char b = data[pixelOffset];
unsigned char g = data[pixelOffset + 1];
unsigned char r = data[pixelOffset + 2];
fputc(b, file);
fputc(g, file);
fputc(r, file);
}
for (int i = 0; i < rowSize - width * 3; i++)
fputc(0, file);
}
fclose(file);
}
int main() {
int width = 256;
int height = 256;
unsigned char* data = (unsigned char*)malloc(width * height * 3);
for (int y = 0; y < height; y++) {
int rowOffset = y * width * 3;
for (int x = 0; x < width; x++) {
int pixelOffset = rowOffset + x * 3;
data[pixelOffset] = x & 0xFF;
data[pixelOffset + 1] = y & 0xFF;
data[pixelOffset + 2] = (x + y) & 0xFF;
}
}
writeBMP("output.bmp", data, width, height);
free(data);
return 0;
}
```
这个代码生成了一个 256x256 像素的 BMP 文件,每个像素的颜色由其 x 和 y 坐标计算得出。你可以根据需要修改这个代码来生成其他大小、颜色和内容的 BMP 文件。