c++image

C++ creating image


I need to create a bitmap from a table of colors:

char image[200][200][3];

First coordinate is width, second height, third colors: RGB. How to do it?


Solution

  • I'm sure you've already checked http://en.wikipedia.org/wiki/BMP_file_format.

    With that information in hand we can write a quick BMP with:

    // setup header structs bmpfile_header and bmp_dib_v3_header before this (see wiki)
    // * note for a windows bitmap you want a negative height if you're starting from the top *
    // * otherwise the image data is expected to go from bottom to top *
    
    FILE * fp = fopen ("file.bmp", "wb");
    fwrite(bmpfile_header, sizeof(bmpfile_header), 1, fp);
    fwrite(bmp_dib_v3_header, sizeof(bmp_dib_v3_header_t), 1, fp);
    
    for (int i = 0; i < 200; i++)  {
     for (int j = 0; j < 200; j++) {
      fwrite(&image[j][i][2], 1, 1, fp);
      fwrite(&image[j][i][1], 1, 1, fp);
      fwrite(&image[j][i][0], 1, 1, fp);
     }
    }
    
    fclose(fp);
    

    If setting up the headers is a problem let us know.

    Edit: I forgot, BMP files expect BGR instead of RGB, I've updated the code (surprised nobody caught it).