【问题标题】:How to crop image into a square如何将图像裁剪成正方形
【发布时间】:2017-08-30 16:58:08
【问题描述】:

您好,我正在尝试将用户上传到我网站上的图像裁剪成一个正方形。我已经尝试了这个网站上发布的一些解决方案,即http://stackoverflow.com/questions/5222711/image-resize-in-c-sharp-algorith-to-determine-resize-dimensions-height-and-wiWebImage Crop To Square。然而,尽管这些解决方案将图像转换为正方形,但它们在图像的顶部和底部添加了大面积的透明区域,这不是我想要的,因为这些图像将用作个人资料图像。

【问题讨论】:

  • 你的问题到底是什么?
  • @Lamar 我的问题是如何在不向顶部和底部添加大块透明度的情况下将图像裁剪成正方形

标签: c# asp.net image


【解决方案1】:

这是我在网站中一直使用的代码:

 public Bitmap MakeSquarePhoto(Bitmap bmp, int size)
        {
            try
            {
                Bitmap res = new Bitmap(size, size);
                Graphics g = Graphics.FromImage(res);
                g.FillRectangle(new SolidBrush(Color.White), 0, 0, size, size);
                int t = 0, l = 0;
                if (bmp.Height > bmp.Width)
                    t = (bmp.Height - bmp.Width) / 2;
                else
                    l = (bmp.Width - bmp.Height) / 2;
                g.DrawImage(bmp, new Rectangle(0, 0, size, size), new Rectangle(l, t, bmp.Width - l * 2, bmp.Height - t * 2), GraphicsUnit.Pixel);
                return res;
            }
            catch { }
        }

【讨论】:

  • 是的,将“return bmp”更改为“return res”使其工作。谢谢。
  • 是的,如果你看我已经在代码中改变了它。我的真实代码获取流并直接保存(不返回任何内容)。我稍微修改了一下以适应你的问题,我犯了一个错误
【解决方案2】:

要裁剪图像而不在顶部和底部添加大块的透明度,您将不得不切掉部分边。在没有看到代码的情况下,它应该是从每边切断 (width-height)/2 个像素的线。

【讨论】:

    猜你喜欢
    • 2013-02-16
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 2020-02-06
    相关资源
    最近更新 更多