在C中创建位图

我正在尝试创建一个显示子弹飞行路径的位图。

int drawBitmap(int height, int width, Point* curve, char* bitmap_name) { int image_size = width * height * 3; int padding = width - (width % 4); struct _BitmapFileheader_ BMFH; struct _BitmapInfoHeader_ BMIH; BMFH.type_[1] = 'B'; BMFH.type_[2] = 'M'; BMFH.file_size_ = 54 + height * padding; BMFH.reserved_1_ = 0; BMFH.reserved_2_ = 0; BMFH.offset_ = 54; BMIH.header_size_ = 40; BMIH.width_ = width; BMIH.height_ = height; BMIH.colour_planes_ = 1; BMIH.bit_per_pixel_ = 24; BMIH.compression_ = 0; BMIH.image_size_ = image_size + height * padding; BMIH.x_pixels_per_meter_ = 2835; BMIH.y_pixels_per_meter_ = 2835; BMIH.colours_used_ = 0; BMIH.important_colours_ = 0; writeBitmap(BMFH, BMIH, curve, bitmap_name); } void* writeBitmap(struct _BitmapFileheader_ file_header, struct _BitmapInfoHeader_ file_infoheader, void* pixel_data, char* file_name) { FILE* image = fopen(file_name, "w"); fwrite((void*)&file_header, 1, sizeof(file_header), image); fwrite((void*)&file_infoheader, 1, sizeof(file_infoheader), image); fwrite((void*)pixel_data, 1, sizeof(pixel_data), image); fclose(image); return 0; } 

曲线是计算路径的函数的返回值。 它指向一个Point数组,它是x和y坐标的结构。 我真的不知道如何正确地将数据“放入”位图。 我最近刚开始编程C,此刻我很丢失。

您已经知道在每个像素行中占用任何松弛空间,但我发现您的计算存在问题。 每个像素行的length % 4 == 0必须length % 4 == 0 。 所以每像素3个字节(24位)

 length = ((3 * width) + 3) & -4; // -4 as I don't know the int size, say 0xFFFFFFFC 

查找位图的结构 – 也许你已经拥有了。 声明(或分配)图像字节数组大小height * length并用零填充它。 解析子弹轨迹并找到xy坐标的范围。 将这些缩放到位图大小的widthheight 。 现在再次解析子弹轨迹,将坐标缩放到xxyy ,并将三个0xFF字节(您指定的24位颜色)写入arrays中每个子弹位置的正确位置。

 if (xx >= 0 && xx < width && yy >= 0 && yy < height) { index = yy * length + xx * 3; bitmap [index] = 0xFF; bitmap [index + 1] = 0xFF; bitmap [index + 2] = 0xFF; } 

最后将位图信息,标题和图像数据保存到文件中。 如果有效,您可以优化颜色的使用。