I am trying to write a small image processing app in C. Currently I am writing a function thats adds a padding to the image. When padding is even, everything works fine image has given amount of padding that wraps the image. If padding is odd image gets corrupted.
void _add_padding(struct bmp_image* image,int padding){
//construct new images resolution with added padding.
int new_height=image->header.height+(padding*2);
int new_width=image->header.width+(padding*2);
//allocate new image to the memory.
struct pixel** output_pixels=(struct pixel**)malloc(new_height*sizeof(struct pixel*));
for(int i=0;i<new_height;i++){
output_pixels[i]=malloc(new_width*sizeof(struct pixel));
}
//initialize new image with all zeros.
int new_colour=255;
for(int i=0;i<new_height;i++){
for(int j=0;j<new_width;j++){
output_pixels[i][j].red=new_colour;
output_pixels[i][j].green=new_colour;
output_pixels[i][j].blue=new_colour;
}
}
for(int i=padding;i<image->header.height+padding;i++){
for(int j=padding;j<image->header.width+padding;j++){
output_pixels[i][j].red=image->pixels[i-padding][j-padding].red;
output_pixels[i][j].green=image->pixels[i-padding][j-padding].green;
output_pixels[i][j].blue=image->pixels[i-padding][j-padding].blue;
}
}
image->header.height=new_height;
image->header.width=new_width;
for(int i=0;i<image->header.height-2*padding;i++){
free(image->pixels[i]);
}
free(image->pixels);
image->pixels=output_pixels;
}
The image output if given padding is even: even padding img
The image output if given padding is odd: odd padding img
I am aware the problem is probably in these lines:
for(int i=padding;i<image->header.height+padding;i++){
for(int j=padding;j<image->header.width+padding;j++){
output_pixels[i][j].red=image->pixels[i-padding][j-padding].red;
output_pixels[i][j].green=image->pixels[i-padding][j-padding].green;
output_pixels[i][j].blue=image->pixels[i-padding][j-padding].blue;
}
}
I've tried tinkering with the algorithm but this version (even though it produces trash half of the time) still comes as the correct algorithm for the job.
Edit: Solved the problem. Problem was the 4 byte alignment as mentioned below. The reason why even numbers would always work whether they are aligned with 4 bytes or not was simply the result of padding being added to each side of the image so thats a guarenteed multiplication by 2. Since even numbers are -obviously- even, they contain at least a 2 in them so that makes them automaticaly alligned by 4.
Hint:
You probably fell in the old Windows Bitmap trap: every row must be aligned on a 4 bytes boundary, so the row pitch must be a multiple of 4.