C 语言生成BMP 文件

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
以下是一个简单的生成 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 文件
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值