iosimageglreadpixels

how to Rotate image by 90' degree using pixel data of the image?


Currently i m capturing the screen using the glreadpixels(). the image captured is generally mirrored image hence i flipped back the image to normal. Now i want to rotate the captured data (image) by 90'degree. any idea how to do that ?

The code i m using to capture the screen data is :

CGRect screenBounds = [[UIScreen mainScreen] bounds];

int backingWidth = screenBounds.size.width;
int backingHeight =screenBounds.size.height;

glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);


NSInteger myDataLength = backingWidth * backingHeight * 4;
GLuint *buffer;
if((buffer= (GLuint *) malloc(myDataLength)) == NULL )
    NSLog(@"error initializing the buffer");
glReadPixels(0, 0, backingWidth, backingHeight, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
// code for flipping back (mirroring the image data)    
for(int y = 0; y < backingHeight / 2; y++) {
    for(int xt = 0; xt < backingWidth; xt++) {
        GLuint top = buffer[y * backingWidth + xt];
        GLuint bottom = buffer[(backingHeight - 1 - y) * backingWidth + xt];
        buffer[(backingHeight - 1 - y) * backingWidth + xt] = top;
        buffer[y * backingWidth + xt] = bottom;
    }
}

Any idea how to rotate the data captured in buffer by 90'degree ? Thanks


Solution

  • size_t at (size_t x, size_t y, size_t width)
    {
        return y*width + x;
    }
    
    void rotate_90_degrees_clockwise (
        const pixel * in,
        size_t in_width,
        size_t in_height,
        pixel * out)
    {
        for (size_t x = 0; x < in_width; ++x) {
            for (size_t y = 0; y < in_height; ++i)
                out [at (in_height-y, in_width-x, in_height)]
                   = in [at (x, y, in_width)];
        }
    }
    

    Sometimes, nothing beats a minute with pencil-and-paper :-)

    This could be optimised, if you maintain x_in and y_in versus x_out and y_out -- incrementing one and decrementing the other -- and by cacheing x in between the loops, but this is the basic idea.