c# - 旋转时调整图像大小

标签 c# winforms visual-studio

我正在尝试旋转图像。我有一个 pictureBox 369x276。但是当我旋转时,这个尺寸会减小。

pictureBox sizeMode 是PictureBoxSizeMode.StretchImage

这是我的代码:

        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;

最佳答案

只需使用 RotateFlip:

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

正如@Dan-o 所指出的,这允许旋转 System.Drawing.RotateFlipType 中的任何度数。枚举。

要在不丢失大小的情况下旋转任意角度的位图,您可以执行以下操作,但这有点复杂!

一个 - 添加 WriteableBitmapEx库到你的项目

- 将 XAML、WindowsBase 和 PresentationCore 库添加到您的项目

- 使用以下方法将位图旋转任意度数:

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;
    }
}

屁股疼,但有效!

关于c# - 旋转时调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15415617/

相关文章:

visual-studio - MSBuild:将来自不同来源的信息合并到一项任务中

c# - 是否可以在运行时将数据库添加到动态数据网站 (ASP.NET)?

c# - WinForm无法滚动到底部

来自 byte[] 的 C# LoadLibrary

C#读取Excel文件时出错,这是一个奇怪的错误

c# - BMP 中的字节到位得到 RGB

sql-server - VS 数据库项目主键名称

visual-studio - NuGet包浏览: How to see packages ordered by download count (descending)

c# - 为测验评分的正确方法

c# - Azure 事件中心分区编号和发送到特定分区