Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ creating image

Tags:

c++

image

I haven't been programming in C++ for a while, and now I have to write a simple thing, but it's driving me nuts.

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?

Thanks for any help. Adam

like image 880
Adam Avatar asked Dec 07 '09 22:12

Adam


3 Answers

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).

like image 96
Ron Warholic Avatar answered Oct 29 '22 16:10

Ron Warholic


It would be advisable to initialise the function as a simple 1 dimensional array.

ie (Where bytes is the number of bytes per pixel)

 char image[width * height * bytes];

You can then access the relevant position in the array as follows

 char byte1 = image[(x * 3) + (y * (width * bytes)) + 0];
 char byte2 = image[(x * 3) + (y * (width * bytes)) + 1];
 char byte3 = image[(x * 3) + (y * (width * bytes)) + 2];
like image 38
Goz Avatar answered Oct 29 '22 17:10

Goz


I would first try to find out, how the BMP file format (that's what you mean by a bitmap, right?) is defined. Then I would convert the array to that format and print it to the file.

If that's an option, I would also consider trying to find an existing library for BMP files creation, and just use it.

Sorry if what I said is already obvious for you, but I don't know on which stage of the process you are stuck.

like image 36
Igor Avatar answered Oct 29 '22 16:10

Igor