0

I am trying to add rotating of image in my WPF application. There is a code:

public static Bitmap RotateImage(Image inputImage, float angleDegrees)
{
    if (angleDegrees == 0f || angleDegrees == 360f)
        return (Bitmap)inputImage.Clone();

    int oldWidth = inputImage.Width;
    int oldHeight = inputImage.Height;
    int newWidth = inputImage.Width;
    int newHeight = inputImage.Height;

    Bitmap newBitmap = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppArgb);
    newBitmap.SetResolution(inputImage.HorizontalResolution, inputImage.VerticalResolution);

    using (Graphics graphicsObject = Graphics.FromImage(newBitmap))
    {
        graphicsObject.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphicsObject.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphicsObject.SmoothingMode = SmoothingMode.HighQuality;

        graphicsObject.TranslateTransform(newWidth / 2f, newHeight / 2f);
        graphicsObject.RotateTransform(angleDegrees);
        graphicsObject.TranslateTransform(-oldWidth / 2f, -oldHeight / 2f);

        graphicsObject.DrawImage(inputImage, 0, 0);
    }

    return newBitmap;
}

Original code: https://stackoverflow.com/a/16027561/11601385

Well, the image is rotated correctly, but there is a problem with image size.

Before rotation After rotation

How can I change size of rotated image to make it correct?

Airn5475
  • 2,452
  • 29
  • 51
Ether
  • 28
  • 7
  • If you are rotating +90 / -90 (or +270) degrees, then the newWidth = oldHeight and newHeight = oldWidth. – Gerardo Grignoli Aug 07 '20 at 14:14
  • 1
    The original post you're quoting is a WinForms question, are you sure you wanna get inspiration from that for your WPF question? – Corentin Pane Aug 07 '20 at 14:15
  • The size you need is a matter of simple math. – TaW Aug 07 '20 at 14:25
  • Just set the LayoutTransform or RenderTransform of the Image element that shows the bitmap. Use a RotateTransform. – Clemens Aug 07 '20 at 16:14
  • See if this works for you https://stackoverflow.com/questions/12655033/rotate-3d-cube-in-wpf/12655670#12655670 – Mark Hall Aug 07 '20 at 20:40
  • You're rotating a rectangular picture? As you rotate, it shouldn't be too surprising when it doesn't fit. You need to work out what size rectangle will fit and scale it down. I think this is what is being done here https://stackoverflow.com/questions/36540965/rotate-and-scale-rectangle-as-per-user-control – Andy Aug 08 '20 at 16:59

0 Answers0