Правильно повернуть изображение - PullRequest
0 голосов
/ 25 октября 2018

enter image description here

Как повернуть изображение, чтобы оно не показывалось так?

Вот мой метод поворота:

public static Bitmap RotateImageN(Bitmap bmp, float angle)
    {
        Bitmap rotatedImage = new Bitmap(bmp.Width, bmp.Height);
        using (Graphics g = Graphics.FromImage(rotatedImage))
        {
            // Set the rotation point to the center in the matrix
            g.TranslateTransform(bmp.Width / 2, bmp.Height / 2);
            // Rotate
            g.RotateTransform(angle);
            // Restore rotation point in the matrix
            g.TranslateTransform(-bmp.Width / 2, -bmp.Height / 2);
            // Draw the image on the bitmap
            g.DrawImage(bmp, new Point(0, 0));
        }

        return rotatedImage;
    }

Редактировать: После попытки ввода кода Лусида

enter image description here

Ответы [ 2 ]

0 голосов
/ 25 октября 2018

Проблема возникает при вращении, связанном с ограничительной рамкой.Он обрезает края, потому что изображение, которое вы предоставили, не вписывается в область, которую вы дали.

Я также столкнулся с этой проблемой.Поэтому я попробовал решение из здесь .

Добавление кода, который работает для меня.

public static Bitmap RotateImageN(Bitmap bitmap, float angle)
{
    Matrix matrix = new Matrix();
    matrix.Translate(bitmap.Width / -2, bitmap.Height / -2, MatrixOrder.Append);
    matrix.RotateAt(angle, new System.Drawing.Point(0, 0), MatrixOrder.Append);
    using (GraphicsPath graphicsPath = new GraphicsPath())
    {
        graphicsPath.AddPolygon(new System.Drawing.Point[] { new System.Drawing.Point(0, 0), new System.Drawing.Point(bitmap.Width, 0), new System.Drawing.Point(0, bitmap.Height) });
        graphicsPath.Transform(matrix);
        System.Drawing.PointF[] points = graphicsPath.PathPoints;

        Rectangle rectangle = boundingBox(bitmap, matrix);
        Bitmap resultBitmap = new Bitmap(rectangle.Width, rectangle.Height);

        using (Graphics gDest = Graphics.FromImage(resultBitmap))
        {
            Matrix mDest = new Matrix();
            mDest.Translate(resultBitmap.Width / 2, resultBitmap.Height / 2, MatrixOrder.Append);
            gDest.Transform = mDest;
            gDest.DrawImage(bitmap, points);
            return resultBitmap;
        }
    }
}

private static Rectangle boundingBox(Image image, Matrix matrix)
{
    GraphicsUnit graphicsUnit = new GraphicsUnit();
    Rectangle boundingRectangle = Rectangle.Round(image.GetBounds(ref graphicsUnit));
    Point topLeft = new Point(boundingRectangle.Left, boundingRectangle.Top);
    Point topRight = new Point(boundingRectangle.Right, boundingRectangle.Top);
    Point bottomRight = new Point(boundingRectangle.Right, boundingRectangle.Bottom);
    Point bottomLeft = new Point(boundingRectangle.Left, boundingRectangle.Bottom);
    Point[] points = new Point[] { topLeft, topRight, bottomRight, bottomLeft };
    GraphicsPath graphicsPath = new GraphicsPath(points, new byte[] { (byte)PathPointType.Start, (byte)PathPointType.Line, (byte)PathPointType.Line, (byte)PathPointType.Line });
    graphicsPath.Transform(matrix);
    return Rectangle.Round(graphicsPath.GetBounds());
}
0 голосов
/ 25 октября 2018

Ваше rotatedImage Растровое изображение должно быть достаточно большим, чтобы вместить повернутое изображение.

Скажем, вы повернули исходное изображение на 30 °, вам нужно получить размер ограничительной рамки следующим образом:

enter image description here

Использование некоторого базового триггера:

x = L*cos(30 * π / 180) + w*cos(60 * π / 180)

y = L*sin(30 * π / 180) + w*sin(60 * π / 180)

Поэтому изменитеначало вашего кода:

var x = bmp.Width * Math.Cos(angle * Math.PI / 180) + bmp.Height * Math.Cos((90-angle) * Math.PI / 180)
var y = bmp.Width * Math.Sin(angle * Math.PI / 180) + bmp.Height * Math.Sin((90-angle) * Math.PI / 180)
Bitmap rotatedImage = new Bitmap(x, y);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...