在 C# 中旋转图像时如何防止剪切?

发布于 2024-08-23 06:02:07 字数 1179 浏览 5 评论 0原文

我刚刚经历了很多事情,试图找出如何让图像旋转。这是可行的,但现在它正在剪切,我不太确定如何让它停止...我正在使用这个rotateImage方法:

public static Image RotateImage(Image img, float rotationAngle)
    {
        //create an empty Bitmap image
        Bitmap bmp = new Bitmap(img.Width, img.Height);

        //turn the Bitmap into a Graphics object
        Graphics gfx = Graphics.FromImage(bmp);

        //now we set the rotation point to the center of our image
        gfx.TranslateTransform((float)bmp.Width / 2, (float)bmp.Height / 2);

        //now rotate the image
        gfx.RotateTransform(rotationAngle);

        gfx.TranslateTransform(-(float)bmp.Width / 2, -(float)bmp.Height / 2);

        //set the InterpolationMode to HighQualityBicubic so to ensure a high
        //quality image once it is transformed to the specified size
        gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;

        //now draw our new image onto the graphics object
        gfx.DrawImage(img, new System.Drawing.Point(0, 0));

        //dispose of our Graphics object
        gfx.Dispose();

        //return the image
        return bmp;
    }

我尝试使空位图变大,但这只适用于一侧,因为图像被固定到位图的左上角。任何想法将不胜感激!

I just went through a bunch of stuff trying to figure out how to get the image to even rotate. That works but now it's clipping and I'm not really sure how to make it stop... I'm using this rotateImage method:

public static Image RotateImage(Image img, float rotationAngle)
    {
        //create an empty Bitmap image
        Bitmap bmp = new Bitmap(img.Width, img.Height);

        //turn the Bitmap into a Graphics object
        Graphics gfx = Graphics.FromImage(bmp);

        //now we set the rotation point to the center of our image
        gfx.TranslateTransform((float)bmp.Width / 2, (float)bmp.Height / 2);

        //now rotate the image
        gfx.RotateTransform(rotationAngle);

        gfx.TranslateTransform(-(float)bmp.Width / 2, -(float)bmp.Height / 2);

        //set the InterpolationMode to HighQualityBicubic so to ensure a high
        //quality image once it is transformed to the specified size
        gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;

        //now draw our new image onto the graphics object
        gfx.DrawImage(img, new System.Drawing.Point(0, 0));

        //dispose of our Graphics object
        gfx.Dispose();

        //return the image
        return bmp;
    }

I tried making the empty bitmap larger but that only works for one side since the image is pinned to the upper left corner of the bitmap. Any ideas would be appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

计㈡愣 2024-08-30 06:02:07

我从另一个网站找到了一些帮助。这就是我最终为那些想知道的人所做的事情:

// Rotates the input image by theta degrees around center.
    public static Bitmap RotateImage(Bitmap bmpSrc, float theta)
    {
        Matrix mRotate = new Matrix();
        mRotate.Translate(bmpSrc.Width / -2, bmpSrc.Height / -2, MatrixOrder.Append);
        mRotate.RotateAt(theta, new System.Drawing.Point(0, 0), MatrixOrder.Append);
        using (GraphicsPath gp = new GraphicsPath())
        {  // transform image points by rotation matrix
            gp.AddPolygon(new System.Drawing.Point[] { new System.Drawing.Point(0, 0), new System.Drawing.Point(bmpSrc.Width, 0), new System.Drawing.Point(0, bmpSrc.Height) });
            gp.Transform(mRotate);
            System.Drawing.PointF[] pts = gp.PathPoints;

            // create destination bitmap sized to contain rotated source image
            Rectangle bbox = boundingBox(bmpSrc, mRotate);
            Bitmap bmpDest = new Bitmap(bbox.Width, bbox.Height);

            using (Graphics gDest = Graphics.FromImage(bmpDest))
            {  // draw source into dest
                Matrix mDest = new Matrix();
                mDest.Translate(bmpDest.Width / 2, bmpDest.Height / 2, MatrixOrder.Append);
                gDest.Transform = mDest;
                gDest.DrawImage(bmpSrc, pts);
                return bmpDest;
            }
        }
    }

    private static Rectangle boundingBox(Image img, Matrix matrix)
    {
        GraphicsUnit gu = new GraphicsUnit();
        Rectangle rImg = Rectangle.Round(img.GetBounds(ref gu));

        // Transform the four points of the image, to get the resized bounding box.
        System.Drawing.Point topLeft = new System.Drawing.Point(rImg.Left, rImg.Top);
        System.Drawing.Point topRight = new System.Drawing.Point(rImg.Right, rImg.Top);
        System.Drawing.Point bottomRight = new System.Drawing.Point(rImg.Right, rImg.Bottom);
        System.Drawing.Point bottomLeft = new System.Drawing.Point(rImg.Left, rImg.Bottom);
        System.Drawing.Point[] points = new System.Drawing.Point[] { topLeft, topRight, bottomRight, bottomLeft };
        GraphicsPath gp = new GraphicsPath(points,
                                                            new byte[] { (byte)PathPointType.Start, (byte)PathPointType.Line, (byte)PathPointType.Line, (byte)PathPointType.Line });
        gp.Transform(matrix);
        return Rectangle.Round(gp.GetBounds());
    }

I found some help from another website. Here's what I ended up doing for those of you who want to know:

// Rotates the input image by theta degrees around center.
    public static Bitmap RotateImage(Bitmap bmpSrc, float theta)
    {
        Matrix mRotate = new Matrix();
        mRotate.Translate(bmpSrc.Width / -2, bmpSrc.Height / -2, MatrixOrder.Append);
        mRotate.RotateAt(theta, new System.Drawing.Point(0, 0), MatrixOrder.Append);
        using (GraphicsPath gp = new GraphicsPath())
        {  // transform image points by rotation matrix
            gp.AddPolygon(new System.Drawing.Point[] { new System.Drawing.Point(0, 0), new System.Drawing.Point(bmpSrc.Width, 0), new System.Drawing.Point(0, bmpSrc.Height) });
            gp.Transform(mRotate);
            System.Drawing.PointF[] pts = gp.PathPoints;

            // create destination bitmap sized to contain rotated source image
            Rectangle bbox = boundingBox(bmpSrc, mRotate);
            Bitmap bmpDest = new Bitmap(bbox.Width, bbox.Height);

            using (Graphics gDest = Graphics.FromImage(bmpDest))
            {  // draw source into dest
                Matrix mDest = new Matrix();
                mDest.Translate(bmpDest.Width / 2, bmpDest.Height / 2, MatrixOrder.Append);
                gDest.Transform = mDest;
                gDest.DrawImage(bmpSrc, pts);
                return bmpDest;
            }
        }
    }

    private static Rectangle boundingBox(Image img, Matrix matrix)
    {
        GraphicsUnit gu = new GraphicsUnit();
        Rectangle rImg = Rectangle.Round(img.GetBounds(ref gu));

        // Transform the four points of the image, to get the resized bounding box.
        System.Drawing.Point topLeft = new System.Drawing.Point(rImg.Left, rImg.Top);
        System.Drawing.Point topRight = new System.Drawing.Point(rImg.Right, rImg.Top);
        System.Drawing.Point bottomRight = new System.Drawing.Point(rImg.Right, rImg.Bottom);
        System.Drawing.Point bottomLeft = new System.Drawing.Point(rImg.Left, rImg.Bottom);
        System.Drawing.Point[] points = new System.Drawing.Point[] { topLeft, topRight, bottomRight, bottomLeft };
        GraphicsPath gp = new GraphicsPath(points,
                                                            new byte[] { (byte)PathPointType.Start, (byte)PathPointType.Line, (byte)PathPointType.Line, (byte)PathPointType.Line });
        gp.Transform(matrix);
        return Rectangle.Round(gp.GetBounds());
    }
撩起发的微风 2024-08-30 06:02:07

请按照下列步骤操作:

  1. 创建空的目标图像,其宽度和宽度为高度 = 旋转图像的边界框
  2. 将源图像绘制到目标图像上。源的 (0,0) 将映射到目标的 (ox,oy)
  3. 现在执行旋转目标图像的步骤。

完成上述步骤的详细信息:

W,H = 宽度 &目的地高度

w,h = 宽度 &源高度

c=|cos(theta)|

s=|sin(θ)|

w * c + h * s = W

w * s + h * c = H

ox = ( W - w ) / 2

oy = ( H - h ) / 2

follow these steps:

  1. Create empty destination image whose width & height = bounding box of your rotated image
  2. Draw your source image onto the destination image. (0,0) of source will map to (ox,oy) of destination
  3. Now do the steps to rotate the destination image.

Details to accomplish above steps:

W,H = width & height of destination

w,h = width & height of source

c=|cos(theta)|

s=|sin(theta)|

w * c + h * s = W

w * s + h * c = H

ox = ( W - w ) / 2

oy = ( H - h ) / 2

苍白女子 2024-08-30 06:02:07
public Bitmap rotateImage(Bitmap b, float angle)
    {
        if (angle > 0)
        {
            int l = b.Width;
            int h = b.Height;
            double an = angle * Math.PI / 180;
            double cos = Math.Abs(Math.Cos(an));
            double sin = Math.Abs(Math.Sin(an));
            int nl = (int)(l * cos + h * sin);
            int nh = (int)(l * sin + h * cos);
            Bitmap returnBitmap = new Bitmap(nl, nh);
            Graphics g = Graphics.FromImage(returnBitmap);
            g.TranslateTransform((float)(nl-l) / 2, (float)(nh-h) / 2);
            g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
            g.RotateTransform(angle);
            g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
            g.DrawImage(b, new Point(0, 0));
            return returnBitmap;
        }
        else return b;
    }
public Bitmap rotateImage(Bitmap b, float angle)
    {
        if (angle > 0)
        {
            int l = b.Width;
            int h = b.Height;
            double an = angle * Math.PI / 180;
            double cos = Math.Abs(Math.Cos(an));
            double sin = Math.Abs(Math.Sin(an));
            int nl = (int)(l * cos + h * sin);
            int nh = (int)(l * sin + h * cos);
            Bitmap returnBitmap = new Bitmap(nl, nh);
            Graphics g = Graphics.FromImage(returnBitmap);
            g.TranslateTransform((float)(nl-l) / 2, (float)(nh-h) / 2);
            g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
            g.RotateTransform(angle);
            g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
            g.DrawImage(b, new Point(0, 0));
            return returnBitmap;
        }
        else return b;
    }
奢望 2024-08-30 06:02:07

旋转的图像可能需要包含更大的位图而不进行剪切。计算边界的一种相当简单的方法是将变换矩阵应用于原始边界矩形的角。由于新位图较大,因此必须将原始图像绘制为居中,而不是位于 (0,0)。

这在您的代码的以下修订中得到了证明:

public static Image RotateImage(Image img, float rotationAngle)
{
    int minx = int.MaxValue, maxx = int.MinValue, miny = int.MaxValue, maxy = int.MinValue;

    using (Bitmap bmp = new Bitmap(1, 1)) // Dummy bitmap, so we can use TransformPoints to figure out the correct size.
    {
        using (Graphics g = Graphics.FromImage(bmp))
        {
            g.TranslateTransform((float)img.Width / 2, (float)img.Height / 2);
            g.RotateTransform(rotationAngle);
            g.TranslateTransform(-(float)img.Width / 2, -(float)img.Height / 2);

            Point[] pts = new Point[4];
            pts[0] = new Point(0, 0);
            pts[1] = new Point(img.Width, 0);
            pts[2] = new Point(img.Width, img.Height);
            pts[3] = new Point(0, img.Height);
            g.TransformPoints(CoordinateSpace.Device, CoordinateSpace.World, pts);

            foreach (Point pt in pts)
            {
                minx = Math.Min(minx, pt.X);
                maxx = Math.Max(maxx, pt.X);
                miny = Math.Min(miny, pt.Y);
                maxy = Math.Max(maxy, pt.Y);
            }
        }
    }

    Bitmap bmp2 = new Bitmap(maxx - minx, maxy - miny);
    using (Graphics g = Graphics.FromImage(bmp2))
    {
        g.TranslateTransform((float)bmp2.Width / 2, (float)bmp2.Height / 2);
        g.RotateTransform(rotationAngle);
        g.TranslateTransform(-(float)bmp2.Width / 2, -(float)bmp2.Height / 2);
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(img, bmp2.Width / 2 - img.Width / 2, bmp2.Height / 2 - img.Height / 2);
    }

    return bmp2;
}

A rotated image may require a larger bitmap to be contained without clipping. A fairly simple way to compute the bounds is to apply the transformation matrix to the corners of the original bounding rectangle. Since the new bitmap is larger, the original image must be drawn such that it is centered, rather than at (0,0).

This is demonstrated in the following revision to your code:

public static Image RotateImage(Image img, float rotationAngle)
{
    int minx = int.MaxValue, maxx = int.MinValue, miny = int.MaxValue, maxy = int.MinValue;

    using (Bitmap bmp = new Bitmap(1, 1)) // Dummy bitmap, so we can use TransformPoints to figure out the correct size.
    {
        using (Graphics g = Graphics.FromImage(bmp))
        {
            g.TranslateTransform((float)img.Width / 2, (float)img.Height / 2);
            g.RotateTransform(rotationAngle);
            g.TranslateTransform(-(float)img.Width / 2, -(float)img.Height / 2);

            Point[] pts = new Point[4];
            pts[0] = new Point(0, 0);
            pts[1] = new Point(img.Width, 0);
            pts[2] = new Point(img.Width, img.Height);
            pts[3] = new Point(0, img.Height);
            g.TransformPoints(CoordinateSpace.Device, CoordinateSpace.World, pts);

            foreach (Point pt in pts)
            {
                minx = Math.Min(minx, pt.X);
                maxx = Math.Max(maxx, pt.X);
                miny = Math.Min(miny, pt.Y);
                maxy = Math.Max(maxy, pt.Y);
            }
        }
    }

    Bitmap bmp2 = new Bitmap(maxx - minx, maxy - miny);
    using (Graphics g = Graphics.FromImage(bmp2))
    {
        g.TranslateTransform((float)bmp2.Width / 2, (float)bmp2.Height / 2);
        g.RotateTransform(rotationAngle);
        g.TranslateTransform(-(float)bmp2.Width / 2, -(float)bmp2.Height / 2);
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(img, bmp2.Width / 2 - img.Width / 2, bmp2.Height / 2 - img.Height / 2);
    }

    return bmp2;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文