2017-08-30 176 views
1

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

+0

你的问题是什么呢? – Lamar

+0

@Lamar我的问题是如何将图像裁剪成正方形而不增加顶部和底部的大片透明度 – Zaif

回答

0

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

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 { } 
     } 
+0

是的,将“return bmp”更改为“return res”使其工作。谢谢。 – Zaif

+0

是的,如果你看,我已经改变了它的代码。我的真实代码获取流并直接保存(不返回任何内容)。我改变了一些以适应你的问题,并且我犯了一个错误 –

0

若要在不向顶部和底部添加大片透明度的情况下裁剪图像,您将不得不切掉部分边。在没有看到代码的情况下,它应该是沿着从每边切掉(宽度 - 高度)/ 2像素的线的东西。