Search code examples
opengl-estextures

How to Crop and Scale a Texture in OpenGL


I have an input texture that is 852x640 and an output texture that is 612x612. I am passing the input through a shader and want the output to be scaled and cropped properly. I'm having trouble getting the squareCoordinates, textureCoordinates and viewPorts to work properly together.

I do not want to just crop, I want to scale it as well to get the most amount of the image as possible. If I were using Photoshop I'd do this in two steps (in OpenGL I'm trying to do this in one step):

  1. Scale the image to 612x814
  2. Crop off the excess 101px at each side

I'm using standard square vertices and texture vertices:

static const GLfloat squareVertices[] = {
    -1.0f, -1.0f,
    1.0f, -1.0f,
    -1.0f,  1.0f,
    1.0f,  1.0f,
};

static const GLfloat squareTextureVertices[] = {
    0.0f, 0.0f,
    1.0f, 0.0f,
    0.0f,  1.0f,
    1.0f,  1.0f
}

I don't exactly know what the viewPort should be.


Solution

  • Viewport would be 612x612 pixels.

    To scale and crop original quad the easiest way would be to set vertices to cover 612x612 rect (in your case we leave squareVertices unchanged), but set texture coordinates so left and right sides are cropped out:

    static const GLfloat squareTextureVertices[] = {
        (852.0f-640.0f)/852.0f*0.5f, 0.0f,
        1.0f - (852.0f-640.0f)/852.0f*0.5f, 0.0f,
        (852.0f-640.0f)/852.0f*0.5f,  1.0f,
        1.0f - (852.0f-640.0f)/852.0f*0.5f,  1.0f
    }