【问题标题】:Rotate and crop automatically with c#使用 c# 自动旋转和裁剪
【发布时间】:2016-10-15 06:53:20
【问题描述】:

我有这张图片

如何使用 c# 裁剪和旋转正方形? 我想自动执行此操作,我首先知道我应该旋转边缘并指向正方形,但是如何? 我想要这样的东西

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 抱歉,这太宽泛了:Detect Largest Contour 然后 Image Transformation ;)
  • 您应该首先发布minimal reproducible example

标签: c# image rotation crop


【解决方案1】:

这是一种可用于在 C# 中旋转图像的方法:

/// <summary>
/// method to rotate an image either clockwise or counter-clockwise
/// </summary>
/// <param name="img">the image to be rotated</param>
/// <param name="rotationAngle">the angle (in degrees).
/// NOTE: 
/// Positive values will rotate clockwise
/// negative values will rotate counter-clockwise
/// </param>
/// <returns></returns>
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 Point(0, 0));

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

    //return the image
    return bmp;
}

您可以使用 Graphics.DrawImage 从位图中将裁剪后的图像绘制到图形对象上。

Rectangle cropRect = new Rectangle(...);
Bitmap src = Image.FromFile(fileName) as Bitmap;
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);

using(Graphics g = Graphics.FromImage(target))
{
   g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), 
                    cropRect,                        
                    GraphicsUnit.Pixel);
}

【讨论】:

    猜你喜欢
    • 2013-04-21
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多