使用C生成位图图像:第一行像素损坏

时间:2020-09-30 20:02:06

标签: c data-structures bitmap

我正在尝试使用C生成位图。

到目前为止,我设法编写了这段代码,为我生成了10x10像素大小的图像。

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


#pragma pack(push, 1)
typedef struct {             // Total: 54 bytes
  char bitmapSignatureBytes[2];
  uint32_t  size;             // File size in bytes
  uint16_t  reserved1;        // Not used
  uint16_t  reserved2;        // Not used
  uint32_t  offset;           // Offset to image data in bytes from beginning of file (54 bytes)
  uint32_t  dib_header_size;  // DIB Header size in bytes (40 bytes)
  int32_t   width;         // Width of the image
  int32_t   height;        // Height of image
  uint16_t  num_planes;       // Number of color planes
  uint16_t  bits_per_pixel;   // Bits per pixel
  uint32_t  compression;      // Compression type
  uint32_t  image_size_bytes; // Image size in bytes
  int32_t   x_resolution_ppm; // Pixels per meter
  int32_t   y_resolution_ppm; // Pixels per meter
  uint32_t  num_colors;       // Number of colors  
  uint32_t  important_colors; // Important colors 
} BMPHeader;
#pragma pack(pop)

const int32_t image_width = 10;
const int32_t image_height = 10;

const int32_t bitcount = 24;//<- 24-bit bitmap
const int32_t width_in_bytes = ((image_width * bitcount + 31) / 32) * 4;
const uint32_t imagesize = width_in_bytes * image_height;   //total image size
BMPHeader bmpHeader = {"BM", 54+imagesize, 0, 0, 54, 40, image_width, image_height, 1, 24, 0, imagesize, 100, 100, 0, 0};

 // porque usar pragma:  https://stackoverflow.com/questions/3318410/pragma-pack-effect

typedef struct 
{
    uint8_t blue;
    uint8_t green;
    uint8_t red; 
    
}pixel;

pixel pixelConfig = {255, 255, 255};

int main(void)
{




    FILE *file = fopen("my_first_image.bmp", "wb");

    // Print (write) strings to file
    fwrite(&bmpHeader, sizeof(bmpHeader), 1, file);


    int size = bmpHeader.width*bmpHeader.height;
    for (int i = 0; i < size; ++i)
    {
        fwrite(&pixelConfig, sizeof(pixelConfig), 1, file);
    }

    // Close file
    fclose(file);
}

我的问题是最终文件似乎已损坏,并且第一行像素始终显示为随机颜色。其他以下几行都可以。

我在代码中找不到错误。也许有人会告诉我怎么回事?

我想它与我的fileHeader和infoHeader有关。 我尝试检查两者的大小是否相加,结果达到了54bytes。

另一个假设是尝试处理填充(我认为这是最有可能解决该问题的方法),但我不明白我需要如何使用它。

请帮我了解为什么我的图像损坏了。我正在发送一个示例,其中包含我可以使用上述代码生成的图像。

The result image of code above

1 个答案:

答案 0 :(得分:1)

没有填充,这使文件太短。我不清楚为什么其他颜色会出现。添加填充使问题消失了。例如,

uint8_t zero[4] = { 0 };
int size = bmpHeader.width * bmpHeader.height;
for (int i = 0; i < bmpHeader.height; ++i)
{
    for (int j = 0; j < bmpHeader.width; j++)
        fwrite(&pixelConfig, sizeof(pixelConfig), 1, file);
    int32_t width_in_bytes_unrounded = bmpHeader.width * 3;
    fwrite(zero, 1, width_in_bytes - width_in_bytes_unrounded, file);
}