我想分享我的解决方案,该解决方案基于选定的答案。此代码将图像调整大小并裁剪为圆形,对边缘应用抗锯齿。它还可以防止鼠标悬停或调整窗口大小时图像丢失。裁剪后的图像可以轻松保存。
/// <summary>Redimensiona y recorta la imagen en forma de Circulo (con Antialias).</summary>
/// <param name="srcImage">Imagen Original a Recortar</param>
/// <param name="size">Tamaño deseado (en pixeles)</param>
/// <param name="BackColor">Color de fondo</param>
public static Image CropToCircle(System.Drawing.Image srcImage, Size size, System.Drawing.Color BackColor)
{
System.Drawing.Image Canvas = new System.Drawing.Bitmap(size.Width, size.Height, srcImage.PixelFormat);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(Canvas);
System.Drawing.Rectangle outerRect = new System.Drawing.Rectangle(-1, -1, Canvas.Width + 1, Canvas.Height + 1);
System.Drawing.Rectangle rect = System.Drawing.Rectangle.Inflate(outerRect, -2, -2);
g.DrawImage(srcImage, outerRect);
using (System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(BackColor))
using (System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath())
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
path.AddEllipse(rect);
path.AddRectangle(outerRect);
g.FillPath(brush, path);
}
return Canvas;
}
用法:(所需尺寸为 64x64 像素,白色背景)
System.Drawing.Image img = System.Drawing.Image.FromFile(@"E:\Mis Documentos\Mis imágenes\ergo-proxy-fullon-fight.jpg");
System.Drawing.Image circle = Util.CropToCircle(img, new System.Drawing.Size(64,64), System.Drawing.Color.White);
if (circle != null)
{
this.picUser.Image = circle;
}