【问题标题】:Clip an image in a specific shape .NET以特定形状剪辑图像 .NET
【发布时间】:2016-02-22 14:07:19
【问题描述】:

我的 MVC4 项目中有一个页面,用户可以在其中使用文件上传控件添加其公司徽标。然后,这些图像/徽标会显示在移动应用程序的地图上。我们需要裁剪这些图像,使它们看起来像旗帜。

我们只需要获取标志框架内的图像部分,其余部分保留。

  1. 可以使用 C# 中的代码来完成吗?
  2. 如果是,如何完成。请帮助我提供一些代码示例和链接。
  3. 我需要在上传的图像上显示一个标志框,以便用户可以在该帧中调整其图像,调整它想要在该帧中的样子。

请向我推荐一些 API 和代码示例。

谢谢。

更新:在某些网站中,当我们上传个人资料图片时,它会在顶部为我们提供一个框架,并且我们可以移动我们选择的图像,以便所需的部分进入该框架。现在,当我们上传个人资料图片时,它会调整为该大小。我可以在这里做类似的事情吗?在上面的框架中,我可以给出一个标志形状,用户可以移动上传的图像,以获得该框架中所需的图像部分。 这是正确的方法吗? 我们应该怎么做?我查看了一些 jquery 代码示例,但没有任何帮助。

【问题讨论】:

标签: c# asp.net image asp.net-mvc-4 resize-crop


【解决方案1】:
  // Following code derives a cutout bitmap using a
  // scizzor path as a clipping region (like Paint would do)
  // Result bitmap has a minimal suitable size, pixels outside 
  // the clipping path will be white.

  public static Bitmap ApplyScizzors(Bitmap bmpSource, List<PointF> pScizzor)
    {
        GraphicsPath graphicsPath = new GraphicsPath();   // specified Graphicspath          
        graphicsPath.AddPolygon(pScizzor.ToArray());      // add the Polygon
        var rectCutout = graphicsPath.GetBounds();        // find rectangular range           
        Matrix m = new Matrix();
        m.Translate(-rectCutout.Left, -rectCutout.Top);   // translate clip to (0,0)
        graphicsPath.Transform(m);
        Bitmap bmpCutout = new Bitmap((int)(rectCutout.Width), (int)(rectCutout.Height));  // target
        Graphics graphicsCutout = Graphics.FromImage(bmpCutout);
        graphicsCutout.Clip = new Region(graphicsPath);
        graphicsCutout.DrawImage(bmpSource, (int)(-rectCutout.Left), (int)(-rectCutout.Top)); // draw
        graphicsPath.Dispose();
        graphicsCutout.Dispose();
        return bmpCutout;
    }

【讨论】:

    【解决方案2】:

    您可以使用带有 Region 作为参数的 SetClip 函数:

    https://msdn.microsoft.com/en-us/library/x1zb278e(v=vs.110).aspx

    因此,您需要从位图创建 Graphics 对象,将剪辑设置为您的标志形状,然后在该 Graphics 对象上绘制图像。就是这样。

    【讨论】:

    • 谢谢 Dmitry,我正在尝试,会告诉你我得到了什么。
    • 嗨,德米特里。我试过你提供的代码。但它没有用。可能是我错过了什么
    • 能否请将您在 GitHub 上的代码链接发给我(例如)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 2019-09-30
    • 2017-02-14
    相关资源
    最近更新 更多