Image resize when rotate

c#, visual-studio, winforms

Solution

Just use RotateFlip:

Bitmap oldBitmap = (Bitmap)pictureBox1.Image;
oldBitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox1.Image = oldBitmap;

As @Dan-o has pointed out, this allows a rotation of any of the degree's in the System.Drawing.RotateFlipType enum.

To rotate a Bitmap any angle without losing the size, you could do the following, but it's a bit convoluted!

One - Add the WriteableBitmapEx library to your project

Two - Add the XAML, WindowsBase and PresentationCore libraries to your project

Three - Use the following to rotate your Bitmap any amount of degrees:

class Program
{
    static void Main(string[] args)
    {
        Bitmap oldBitmap = (Bitmap)pictureBox1.Image;;

        var bitmapAsWriteableBitmap = new WriteableBitmap(BitmapToBitmapImage(oldBitmap));
        bitmapAsWriteableBitmap.RotateFree(23);

        var rotatedImageAsMemoryStream = WriteableBitmapToMemoryStream(bitmapAsWriteableBitmap);
        oldBitmap = new Bitmap(rotatedImageAsMemoryStream);
    }

    public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
    {
        var memStream = BitmapToMemoryStream(bitmap);
        return MemoryStreamToBitmapImage(memStream);
    }

    public static MemoryStream BitmapToMemoryStream(Bitmap image)
    {
        var memoryStream = new MemoryStream();
        image.Save(memoryStream, ImageFormat.Bmp);

        return memoryStream;
    }

    public static BitmapImage MemoryStreamToBitmapImage(MemoryStream ms)
    {
        ms.Position = 0;
        var bitmap = new BitmapImage();

        bitmap.BeginInit();

        bitmap.StreamSource = ms;
        bitmap.CacheOption = BitmapCacheOption.OnLoad;

        bitmap.EndInit();
        bitmap.Freeze();

        return bitmap;
    }

    private static MemoryStream WriteableBitmapToMemoryStream(WriteableBitmap writeableBitmap)
    {
        var ms = new MemoryStream();

        var encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(writeableBitmap));

        encoder.Save(ms);

        return ms;
    }
}

Pain in the ass, but works!

Problem

I'm trying to rotate the image.. I have a pictureBox 369x276. But when I rotate, this size decrease. The pictureBox sizeMode is PictureBoxSizeMode.StretchImage here is my code: ``` Bitmap oldBitmap = (Bitmap)pictureBox1.Image; float angle = 90; var newBitmap = new Bitmap(oldBitmap.Width, oldBitmap.Height); var graphics = Graphics.FromImage(newBitmap); graphics.TranslateTransform((float)oldBitmap.Width / 2, (float)oldBitmap.Height / 2); graphics.RotateTransform(angle); graphics.TranslateTransform(-(float)oldBitmap.Width / 2, -(float)oldBitmap.Height / 2); graphics.DrawImage(oldBitmap, new Point(0, 0)); pictureBox1.Image = newBitmap; ```

Original source