理解代码以在C中翻转bmp图像

时间:2016-03-24 21:15:57

标签: c bmp

我有一个在C中旋转和缩放bmp图像的任务。我们已经提供了翻转图像的代码,以帮助我们了解它是如何工作的,但我很难这样做。< / p>

int flip (PIXEL *original, PIXEL **new, int rows, int cols) 
{
  int row, col;

  if ((rows <= 0) || (cols <= 0)) return -1;

  *new = (PIXEL*)malloc(rows*cols*sizeof(PIXEL));

  for (row=0; row < rows; row++)
    for (col=0; col < cols; col++) {
      PIXEL* o = original + row*cols + col;
      PIXEL* n = (*new) + row*cols + (cols-1-col);
      *n = *o;
    }

  return 0;
}

1 个答案:

答案 0 :(得分:0)

int flip (PIXEL *original, PIXEL **new, int rows, int cols) 
{
  int row, col;

  if ((rows <= 0) || (cols <= 0)) return -1;

  *new = (PIXEL*)malloc(rows*cols*sizeof(PIXEL)); // Allocate memory for the flipped image

  for (row=0; row < rows; row++)
    for (col=0; col < cols; col++) {
      PIXEL* o = original + row*cols + col;         // Get a pointer to pixel (row, col)
                                                    // in original image

      PIXEL* n = (*new) + row*cols + (cols-1-col);  // Get a pointer to pixel
                                                    // (row, cols - col -1) 
                                                    // in flipped image


      *n = *o;   // Copy pixel from original image to flipped image
    }

  return 0;
}

假设您有2x2图像:

Loop 1: Original (0, 0) is copied to flipped (0, 1)
Loop 2: Original (0, 1) is copied to flipped (0, 0)
Loop 3: Original (1, 0) is copied to flipped (1, 1)
Loop 4: Original (1, 1) is copied to flipped (1, 0)