eitzo
eitzo

Reputation: 103

Create Bitmap in C

I'm trying to create a Bitmap that shows the flightpath of a bullet.

    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;

}

Curve is the return value from the function which calculates the path. It points at an array of Points, which is a struct of x and y coordinates. I don't really know how to "put" the data into the Bitmap correctly. I just started programming C recently and I'm quite lost at the moment.

Upvotes: 2

Views: 1453

Answers (1)

Weather Vane
Weather Vane

Reputation: 34583

You already know about taking up any slack space in each pixel row, but I see a problem in your calculation. Each pixel row must have length % 4 == 0. So with 3 bytes per pixel (24-bit)

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

Look up the structure of a bitmap - perhaps you already have. Declare (or allocate) an image byte array size height * length and fill it with zeros. Parse the bullet trajectory and find the range of x and y coordinates. Scale these to the bitmap size width and height. Now parse the bullet trajectory again, scaling the coordinates to xx and yy, and write three 0xFF bytes (you specified 24-bit colour) into the correct place in the array for each bullet position.

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;
}

Finally save the bitmap info, header and image data to file. When that works, you can refine your use of colour.

Upvotes: 1

Related Questions