Search code examples
c#imagebitmapfilesize

Flipping a bitmap but keeping original file size


I have something that requires the the same filesize after modifying the BMP file, but when I try to flip it, the filesize of the resulting file changes.

Bitmap pic = new Bitmap(input);
pic.RotateFlip(RotateFlipType.Rotate180FlipX);
pic.Save("test.bmp", ImageFormat.Bmp);

Any suggestions?


Solution

  • The problem is, that the original is 16bpp and output is 32bpp. Bitmap is automatically converted to 32bpp, so You just have to convert it back (or use some library, that does not do this conversion automatically on file read):

        Bitmap pic = new Bitmap("example.bmp");
    
        Bitmap pic2 = new Bitmap(pic.Width, pic.Height, PixelFormat.Format16bppRgb555);
    
        for (int x = 0; x < pic.Width; ++x)
        {
            for (int y = 0; y < pic.Height; ++y)
            {
                pic2.SetPixel(x, y, pic.GetPixel(x, y));
            }
        }
    
        pic2.RotateFlip(RotateFlipType.Rotate180FlipX);
        pic2.Save("test.bmp", ImageFormat.Bmp);
    

    The best way to say what happens is to look into the file with hex viewer, bmp format is well documented: https://en.wikipedia.org/wiki/BMP_file_format