Search code examples
opengltexturesglteximage2d

Create A Solid Color Texture In OpenGL


I have a question regarding creating textures without a file. My goal is to make a function that takes a vec3 color as an input and returns a texture ID for that texture.

This is what I have so far, but it gives odd outputs which has stripes of random jumbled colors:

unsigned int colorToTexture(glm::vec3 color, const int size) {
    // Create id for texture
    unsigned int tex;
    // generate and bind texture
    glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_2D, tex);
    // set texture wrap parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // set texture filter parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // set image data
    unsigned char* data = new unsigned char[size * size * sizeof(unsigned char)];
    for (unsigned int i = 0; i < (int)(size * size * sizeof(unsigned char)) / 3; i ++) {
        data[i * 3] = (int)(color.x * 255);
        data[i * 3 + 1] = (int)(color.y * 255);
        data[i * 3 + 2] = (int)(color.z * 255);
    }
    // set texture data and generate mipmaps
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, size, size, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
    glGenerateMipmap(GL_TEXTURE_2D);
    // free image memory
    delete[] data;
    return tex;
}

Here's an example of what it does (Note that it works fine with regular textures generated from loaded files): Wierd output from generated texture


Solution

  • You are uploading only 1/3 data into that texture which is most likely the problem, try this code:

    // set image data
    unsigned char* data = new unsigned char[3 * size * size * sizeof(unsigned char)];
    for (unsigned int i = 0; i < size  * size; i++) 
    {
        data[i * 3] = (unsigned char)(color.x * 255.0f);
        data[i * 3 + 1] = (unsigned char)(color.y * 255.0f);
        data[i * 3 + 2] = (unsigned char)(color.z * 255.0f);
    }
    

    Furthermore, the glTexImage2D call should be this since only RGB values are put into the data variable:

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, size, size, 0, GL_RGB, GL_UNSIGNED_BYTE, data);