如何使用图像的像素数据将图像旋转90度?

时间:2011-07-19 10:39:07

标签: ios image glreadpixels

目前我正在使用glreadpixels()捕获屏幕。捕获的图像通常是镜像图像,因此我将图像翻转回正常。 现在我想将捕获的数据(图像)旋转90'度。 知道怎么做吗?

我用来捕获屏幕数据的代码是:

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;
    }
}

任何想法如何将缓冲区中捕获的数据旋转90'degree? 感谢

2 个答案:

答案 0 :(得分:2)

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)];
    }
}

有时候,没有什么比用铅笔纸快一点了: - )

这可以优化,如果你保持x_in和y_in对x_out和y_out - 递增1并递减另一个 - 并通过在循环之间缓存x,但这是基本的想法。

答案 1 :(得分:2)

k终于我弄明白了。对于其他想要在此处执行相同操作的人来说,将图像从像素数据旋转90度,180度,270度的代码: -

// Rotate 90
// height and width specifies corresponding height and width of image            
  for(int h = 0, dest_col = height - 1; h < height; ++h, --dest_col)
       {
         for(int w = 0; w < width; w++)
            {
               dest[ ( w * height ) + dest_col] = source[h*width + w];
            }
       }




       // Rotate 180

      for( int h=0, dest_row=(height-1); h < height; --dest_row, ++h )
           {
            for ( int w=0, dest_col=(width-1); w < width; ++w, --dest_col )
             {
            dest[ dest_row * width + dest_col] = source[h*width + w];
             }
           }



  // Rotate 270

       for(int h = 0, dest_col=0; h < height; ++dest_col, ++h)
             {
             for(int w=0, dest_row=width-1; w < width; --dest_row, ++w)
             {
              dest[(dest_row * height) + dest_col] = source[ h * width + w];
             }
             }