Reputation: 419
The following code was given to me by my instructor. I just don't understand how this is scaling a bmp image. I know the basics about bmp images (the info on wikipedia). I know that this method is supposed to multiply the rows and cols of the new image by whatever scale is. I tried to run the code by hand but it confused me even more. Any help will be much appreciated. Thanks!
int enlarge(PIXEL* original, int rows, int cols, int scale,
PIXEL** new, int* newrows, int* newcols)
{
//scaling the new rows & cols
*newcols = cols * scale;
*newrows = rows * scale;
//memory allocated for enlaged bmp
*new = (PIXEL*)malloc(*newrows * *newcols * sizeof(PIXEL));
int row, col, sx, sy;
//transverse through every row
for (row = 0; row < rows; row++ )
//transvere through every col
for (col = 0; col < cols; col++ ){
//im unsure what this is for
PIXEL* o = original + (row * cols) + col;
for(sy = 0; sy < scale; sy++ )
for(sx = 0; sx < scale; sx++ )
{
//im unsure what this is for
PIXEL* n = *new + (scale * row) * *newcols + (scale * col) + (sy * *newcols) + sx;
*n = *o;
}
}
return 0;
}
Here is the struct for PIXEL.
typedef struct {
unsigned char r;
unsigned char g;
unsigned char b;
} PIXEL;
There is additional code but I do not think that is needed for this question.
Upvotes: 0
Views: 454
Reputation: 126907
PIXEL* o = original + (row * cols) + col;
Here he is retrieving a pointer to the source pixel in the original image; it's just trivial pointer arithmetic, based on the fact that the rows in the bitmap are consecutive in memory. In general, in a C-style matrix width
-wide the address of the element (x, y) is beginning + (y * width) + x
.
Then, he loops over a square scale
x scale
wide in the target image.
for(sy = 0; sy < scale; sy++ )
for(sx = 0; sx < scale; sx++ )
{
//im unsure what this is for
PIXEL* n = *new + (scale * row) * *newcols + (scale * col) + (sy * *newcols) + sx;
The n
pointer points to the target pixel in the destination image; if you match the formula above from the source image and rearrange a bit the terms, you'll see he is accessing the new image, at position
(scale * col + sx, scale * row + sy)
(remember that the new image is *newcols
wide).
*n = *o;
Here he's just copying the source pixel to the target pixel.
In practice, he's "expanding" each source pixel into a scale x scale square in the target image.
Upvotes: 1