我正在尝试用 C 语言编写一个小型图像处理应用程序。目前我正在编写一个为图像添加填充的函数。当填充均匀时,一切正常,图像具有一定量的填充来包裹图像。如果填充是奇数图像就会损坏。
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;
}
我知道问题可能出在这些方面:
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;
}
}
我尝试过修改算法,但这个版本(尽管它有一半的时间产生垃圾)仍然是这项工作的正确算法。
提示:
您可能陷入了旧的 Windows 位图陷阱:每行必须在 4 字节边界上对齐,因此行间距必须是 4 的倍数。