Regios Regios - 3 years ago 138
C Question

Inverting BMP pictures final result is messed up

I am trying to invert a bmp file and am soooo close to getting the correct output but I have no idea where I went wrong.

[My Output][1]

As with inverting images, the original was white background with the black box and x in the middle. HOWEVER, there was no black line at the top right (my output has a white line near the top right). Any clarification will be appreciated.

Loop that does the inverting:

int index = 0;
while (index < dibHeader.width) {
int index2 = 0;
while (index2< dibHeader.length) {

fread(&pixel.b, 1, 1, file);
unsigned int blue = pixel.b;
blue = ~blue;
pixel.b = (char) blue;

... Same for green/red

fseek(file, -3, SEEK_CUR);
f(write(&pixel.b, 1, 1, file);

... Same for green/red

index2++;
}
index++;
}


Struct for pixels:

struct Pixels {
unsigned char b, g, r;
}


Declaration of pixel

struct Pixels pixel;

Answer Source

The image you have posted has a width of 273 pixels. It appears your code is handling a 24-bit image. The width in 24-bit image has to be padded to make sure it is a multiple of 4.

int padding = dibHeader.width % 4; 

The bitmap is read from bottom to top, row by row, and then column by column. In this case it doesn't matter if you go from top to bottom, but you have to iterate through the rows first, and the columns, and apply the padding for each row.

//24-bit image:
int padding = dibHeader.width % 4;
index = 0;
while(index < dibHeader.height) //<== go through the height
{
    index2 = 0;
    while(index2 < dibHeader.width) 
    {
        fread...
        pixel.r = ~pixel.r;
        pixel.b = ~pixel.b;
        pixel.g = ~pixel.g;

        fseek(f, -3, SEEK_CUR);
        fwrite...
        fflush(f);
        index2++;
    }
    fseek(f, padding, SEEK_CUR); //<== skip padding
    index++;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download