С++, rotate bmp file

I need to rotate the bmp file exactly 180 degrees.(if possible, do not change anything except the RotateImage function.

At the moment, from this picture:

Input image

I get this:

Output image

What is the problem and how to fix it?

Code:

void RotateImage(tagRGBQUAD* RGB, int biSize, FILE* f) {
    int width = 404; // Image width
    int height = 404; // Image height
    fseek(f, 1078, SEEK_SET); // Offset of bitmap data from the header in bytes

    // Create a temporary array to store the pixels
    tagRGBQUAD* temp = new tagRGBQUAD[width * height];

    // Read the image pixels into the temporary array
    fread(temp, sizeof(tagRGBQUAD), width * height, f);

    // Rotate the image 180 degrees without distortion
    for (int y = 0; y < height / 2; y++) {
        for (int x = 0; x < width; x++) {
            int index1 = (y * width + x);
            int index2 = ((height - 1) - y) * width + x;

            // Swap pixels
            tagRGBQUAD tempPixel = temp[index1];
            temp[index1] = temp[index2];
            temp[index2] = tempPixel;
        }
    }

    // Write the modified pixels back to the file
    fseek(f, 1078, SEEK_SET);
    fwrite(temp, sizeof(tagRGBQUAD), width * height, f);

    delete[] temp;
}


int main(int argc, char* argv[])
{
BitMapHeader header;
tagRGBQUAD RGBQuad[256];
BYTE c;
FILE* fb;
char filename[] = "sqw.bmp";
int i;
if (!(fb = fopen(filename, "r+b"))) { printf("file not open"); return 1; }

    header = ReadHeader(fb);
    
    RotateImage(RGBQuad, header.biSize + 14, fb);
    
    fclose(fb);
    return 0;

}

(most of the code had to be trimmed so that stackoverflow would not give an error)

  • 3

    Nitpick: You need to rotate the image by 180 degrees, not the file. The bmp file has a specific order and rotating the file by 180 degrees will mess up the data format.

    – 

  • 1

    Can you post plain text code with minimal `\` characters. Most of them are in invalid locations and must be removed before successful compilation.

    – 




  • The input image is 367×368, not 404×404. More generally, you are hard-coding a bunch of magic numbers in RotateImage; it seems those numbers don’t actually match the contents of the test .bmp file.

    – 




  • 2

    @ThomasMatthews: Back in the days of actual hard drives, my files rotated a lot more than 180 degrees, with no damage at all. 🙂

    – 

  • 1

    I highly recommend using an image library. See Software Recommendations.

    – 

Leave a Comment