'what is the reason of increasing image size in rotation?

I have a c# application that contains an image gallery where I display some pictures. This gallery have some features including left and right rotation. everything is perfect but when I choose a picture from gallery and press rotation button (regardless left or right rotation), size of the picture increase significantly. It should be mentioned that the picture's format is JPEG.

Size of picture before rotation : 278 kb

Size of picture after rotation : 780 kb

My code for rotation is like bellow :

 public Image apply(Image img)
    {  
        Image im = img;
        if (rotate == 1) im.RotateFlip(RotateFlipType.Rotate90FlipNone);
        if (rotate == 2) im.RotateFlip(RotateFlipType.Rotate180FlipNone);
        if (rotate == 3) im.RotateFlip(RotateFlipType.Rotate270FlipNone);

        //file size is increasing after RotateFlip method

        if (brigh != DEFAULT_BRIGH ||
            contr != DEFAULT_CONTR ||
            gamma != DEFAULT_GAMMA)
        {
            using (Graphics g = Graphics.FromImage(im))
            {
                float b = _brigh;
                float c = _contr;
                ImageAttributes derp = new ImageAttributes();
                derp.SetColorMatrix(new ColorMatrix(new float[][]{
                        new float[]{c, 0, 0, 0, 0},
                        new float[]{0, c, 0, 0, 0},
                        new float[]{0, 0, c, 0, 0},
                        new float[]{0, 0, 0, 1, 0},
                        new float[]{b, b, b, 0, 1}}));
                derp.SetGamma(_gamma);
                g.DrawImage(img, new Rectangle(Point.Empty, img.Size),
                    0, 0, img.Width, img.Height, GraphicsUnit.Pixel, derp);
            }
        }
        return im; 
    }

What is the problem?



Solution 1:[1]

Two reasons:

  1. The JPEG compression/encoding/sampling is not optimized as the original JPEG.
  2. JPEG is not transparent. When an image is not rotated 90/180/270 degrees, the rectangular boundary of the image becomes larger.

Solution 2:[2]

You should to keep raw ImageFormat before change the image, and save to file by raw image format. Like bellow code :

using (Image image = Image.FromFile(filePath))
{
    var rawFormat = image.RawFormat;
    image.RotateFlip(angel);
    image.Save(filePath, rawFormat);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 detale
Solution 2 Fred