Very new to OpenGl. I have seen examples online of bitmaps that are loaded into the system from an external file, and bitmaps that are only of 2 colors (they use glBitmap() )
BUT, I am trying to generate a colored bitmap on the fly. RGB I think would be easiest. Supposing I wanted to create a square 100x100 pixels, where each pixel was a random color. How do I manipulate individual pixels in an array that glDrawPixel() will understand?
I know it something to do with the pixel alignment, and using GL_RGB, but I’m very confused how images are actually stored.
thanks in advance,
Yes, GL_RGB and GL_RGBA are most common pixel formats with the data type, GL_UNSIGNED_BYTE (8 bits per component, so, 24bits and 32bits per pixel, respectively).
You need a single contiguous chunk of memory storage to store the pixel data. For example, GL_RGB format with GL_UNSIGNED_BYTE data type, you can allocate memory like this:
GLubyte *image = new GLubyte[width*height*3];
You can modify RGB components of a pixel like this, for example, at a pixel (x,y):
image[width*y+x] = red;
image[width*y+x+1] = green;
image[width*y+x+2] = blue;
image[y][x] = red;
image[y][x] = green;
image[y][x] = blue;
Great! Thank you for the help. I will try it out immediately. I have one final question though.
What does the
do exactly? I’m not sure what the difference between an alignment of 1, 2, 4 or 8 does. How will affect my array?
Here is a general term of data alignment;
For the performance reason, CPU accesses the memory in 2, 4, 8, 16, or 32 byte chunks at a time, instead of reading 1-byte at a time. Data alignment means the address of the data can be evenly divisible by 2 ,4, 8, or any power of 2. If the address of a data is divisible by 4, then the data is 4-byte alignment. The misaligned data will slow down the data access performance.
And, please check this for more details:
GL_UNPACK_ALIGNMENT is to specify the alignment of the pixel which is the first pixel of each row in a image. For example, Let’s say you have 10x10 image, which is non popwer of 2, with 8-bit RGB format (total 3 bytes per pixel), and the address of the first pixel is 0 (for simplicity). Then, the first pixel address of the second line will be 30 (10*3). Since 30 is not divisible by 4, you need to set GL_UNPACK_ALIGNMENT with 1 or 2. Otherwise, the image will not be rendered properly.