Search code examples
cfwritebmp

Writing to a bmp file in C


I am having difficulties when writing to a bmp file. Here is the code where the matrix is allocated:

  // Dynamically allocate matrix for the bitmap and 
  // while doing so, color it in blue.
  Pixel **bmp_matrix = (Pixel**)malloc(config.resolution_height_ * 
                                       sizeof(Pixel*));
  if (bmp_matrix == NULL)
  {
    printf("error: out of memory\n");
    return MEMORY_ERROR;
  }
  int rows = 0;
  for(; rows < config.resolution_height_; rows++)
  {
    bmp_matrix[rows] = (Pixel*)malloc(config.resolution_width_ * 
                                      sizeof(Pixel));
    if (bmp_matrix[rows] == NULL)
    {
      while(--rows >= 0)
        free(bmp_matrix[rows]);
      free(bmp_matrix);
      printf("error: out of memory\n");
      return MEMORY_ERROR;
    }
    int columns = 0;
    for(; columns < config.resolution_width_; columns++)
      {
        bmp_matrix[rows][columns].red_ = 175;
        bmp_matrix[rows][columns].green_ = 175;
        bmp_matrix[rows][columns].blue_ = 255;
      }
  }

Here is the code for writing the pixels:

int height, width, pad_iterator;
  for(height = info_header.height_ - 1; height >= 0; height--)
  {
    // for(width = 0; width < info_header.width_; width++)
    //   fwrite(&bmp_matrix[height][width], sizeof(Pixel), 1, bitmap_file);
    fwrite(&bmp_matrix[height], sizeof(Pixel), info_header.width_, bitmap_file);
    for(pad_iterator = 0; pad_iterator < pad_length; pad_iterator++)
      fwrite(&pad, sizeof(Byte), 1, bitmap_file);
  }

Now, when I use the for loop which is commented, everything works perfectly. The resulting image is OK. However, I am trying to substitute it with a single fwrite so the program would not have to iterate the loop. In this case the resulting image is completely wrong.

Any help?


Solution

  • Your second try is incorrect.

    In your commented write (fwrite(&bmp_matrix[height][width], sizeof(Pixel), 1, bitmap_file);), you use one pixel at address &bmp_matrix[height][width] which is correct.

    But in fwrite(&bmp_matrix[height], sizeof(Pixel), info_header.width_, bitmap_file);, you write bytes from the address &bmp_matrix[height] ... which may be different things depending on the actual declaration of bmp_matrix

    You should use either &bmp_matrix[height][0] ie. the address of first pixel in a row or equivently (as suggested by Peter Schneider) bmp_matrix[height] (without the &) both giving a correct address.