gpt4 book ai didi

c - 尽管遵循以下格式规范,位图写入程序仍无法生成可读图像

转载 作者:太空宇宙 更新时间:2023-11-04 07:44:18 25 4
gpt4 key购买 nike

作为一个更大项目的一部分,我正在用 C 编写一个位图编写器。我遵循了 windows .bmp header 格式规范,并在十六进制编辑器中检查了生成的文件,以将其与功能性 .bmp 图像进行比较,但是我计算机上的所有图像程序都无法打开它。这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#pragma pack(push, 1) /* remove padding from sructs */

void generateBitmap(int width, int height, float dpi, const char* filename, pixel* imgData) {
FILE* bitmap;

struct fHeader {
uint16_t type;
uint32_t size;
uint16_t reserved1;
uint16_t reserved2;
uint32_t offset;
}bmpFileHeader;

struct iHeader {
uint32_t headerSize;
int32_t width;
int32_t height;
uint16_t planes;
uint16_t bitCount;
uint32_t compression;
uint32_t imageSize; /* may be 0 if uncompressed */
int32_t xPPM;
int32_t yPPM;
uint32_t colorEntriesUsed;
uint32_t importantColors;
}bmpImageHeader;

int bytesPerPixel = 3; /* 24 bit color */
uint32_t imgSize = width * height;
uint32_t fileSize = sizeof(bmpFileHeader) + sizeof(bmpImageHeader) + (bytesPerPixel * width * height);
int32_t ppm = dpi * 39;

bmpFileHeader.type = 0x4D42;
bmpFileHeader.size = fileSize;
bmpFileHeader.reserved1 = 0;
bmpFileHeader.reserved2 = 0;
bmpFileHeader.offset = sizeof(bmpFileHeader) + sizeof(bmpImageHeader);

bmpImageHeader.headerSize = sizeof(bmpImageHeader);
bmpImageHeader.width = width;
bmpImageHeader.height = height;
bmpImageHeader.planes = 1;
bmpImageHeader.bitCount = 8 * bytesPerPixel;
bmpImageHeader.compression = 0;
bmpImageHeader.imageSize = bytesPerPixel * height * width;
bmpImageHeader.xPPM = ppm; /* typically set these to zero */
bmpImageHeader.yPPM = ppm;
bmpImageHeader.colorEntriesUsed = 0;
bmpImageHeader.importantColors = 0;

bitmap = fopen(filename, "wb");
fwrite(&bmpFileHeader, 1, sizeof(bmpFileHeader), bitmap);
fwrite(&bmpImageHeader, 1, sizeof(bmpImageHeader), bitmap);

int i;
for (i = 0; i < (width * height); i++) {
fwrite(&imgData[i], 3, sizeof(char), bitmap);
}

fclose(bitmap);
}

int main(void) {
pixel imData[4];

int i;

for(i = 0; i < 4; i++) {
imData[i].r = 32;
imData[i].g = 64;
imData[i].b = 32;
}

generateBitmap(2, 2, 0, "bmptest.bmp", imData);

return 0;
}

最终结果应该只是一个单调的 2x2 图像。我发现一些示例设置了一些更多的 header 值,例如将 imageSize 设置为零,但其他示例像我在这里那样处理它们。

最佳答案

好吧,我终于让它工作了。问题在于像素行之间的偏移填充位。我个人并不认为它有很好的文档记录,但是 .bmp 文件格式需要根据图像的尺寸在每一行的末尾填充空字节。我需要做的就是将这一行添加到像素编写代码中:

int i;
int p;
for (i = 0; i < (width * height); i++) {
fwrite(&imgData[i], 3, sizeof(char), bitmap);
if ((i + 1) % width == 0) { /* if at end of scanline */
for(p = 0; p < (width % 4); p++) {
fputc('\0', bitmap); /* append appropriate # of padding bits */
}
}
}

关于c - 尽管遵循以下格式规范,位图写入程序仍无法生成可读图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58159729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com