Resize image while rotating

I'm trying to rotate the image. I have a pictureBox 369x276. But when I spin, this size decreases.

PictureBox PictureBoxSizeMode.StretchImage Size

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; 
+4
source share
2 answers

Just use RotateFlip:

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

As @ Dan-o noted, this allows you to rotate any degree in the System.Drawing.RotateFlipType enum.

To rotate a raster raster angle without losing size, you can do the following, but it's a bit confusing!

One . Add WriteableBitmapEx to the project

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

Three . Use the following to rotate Bitmap any number 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 it works!

+2
source

Smaller image expected. I never understood why, but Graphics.DrawImage really works only if you provide it with not only the starting location, but also the size. One of the overloads allows you to include size.

+2
source

Source: https://habr.com/ru/post/1469302/


All Articles