OpenGL Image Generator

The idea behind this post is very simple: generate m x n grid of pixels, with each pixel having a random color. Every time the user clicks the mouse or presses the ‘g’ key, a new random color is generated for each pixel. Since we are using the R, G and B components to represent a color, we can have up to 256 * 256 * 256 = 16,777,216 colors per pixel. Assuming m = 512 and n = 512, the total count of pixels is 512 * 512 = 2,704 pixels. The number of possible images that can be generated is 16,777,216 ^ 2,704 = 4.3913556324838811971996510547776e+19535. Suppose we are generating an image every 1 second, then it would take 1.4276931285385069435340105645214e+19528 years to generate all of the possible combinations, including images of our friends, nature, the past, the present, the future or some electronic gadget we have not yet invented. Well, a very unrealistic time. Limiting m x n to 16 x 16 and limiting colors to only black and white, we can generate up to 65,536 images in about 18 hours. Seems possible; maybe even worth doing.

The goal here is to demonstrate the usage of the glDrawPixels function to draw pixels in the frame buffer. First, we will create a 3-dimensional array representing m x n pixels having 3 color components.

GLubyte buffer[m][n][3];

Next, we need to generate random colors for each pixel.

//  Generate new image with random colors
void generateImage ()
    int i, j;

    for (i = 0; i < WINDOW_WIDTH; i++)
        for (j = 0; j < WINDOW_HEIGHT; j++)
            buffer[i][j][0] = (GLubyte) (rand () % 256);
            buffer[i][j][1] = (GLubyte) (rand () % 256);
            buffer[i][j][2] = (GLubyte) (rand () % 256);

Finally, we pass the buffer to the glDrawPixels, which will write the pixel data from the memory into the frame buffer.

void display ()
    glDrawPixels(m, n, GL_RGB, GL_UNSIGNED_BYTE, buffer);
    glutSwapBuffers ();

Download full source code from my GitHub page. If you have any issues compiling or running the app, check out this blog post for details about compiling and running an OpenGL app that uses the GLUT library.


One thought on “OpenGL Image Generator

  1. I’ll right away take hold of your rss feed as I can not to find your e-mail subscription link or newsletter service. Do you have any? Please permit me recognise so that I could subscribe. Thanks.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s