我正在尝试将图像裁剪为圆形,其中圆形之外的区域是白色的。
新的图像尺寸将与原始图像尺寸相同,只是有效地舍入图像。
我熟悉如何使用 GDI+ 裁剪图像,通过获取现有图像并将其复制到新图像中来绘制矩形/正方形,但我不知道如何用白色填充圆弧/圆形的外部。
这可能吗?
更新 - 我想在服务器端进行,因为不同的浏览器/平台以不同的方式呈现CSS半径,或者根本不呈现
到目前为止我的工作是:
public static Image CropCircle2(Image imgSource)
{
Image imgTarget = new Bitmap(imgSource.Width, imgSource.Height);
Graphics g = Graphics.FromImage(imgTarget);
var path = new System.Drawing.Drawing2D.GraphicsPath();
path.AddEllipse(0, 0, imgTarget.Width, imgTarget.Height);
g.SetClip(path);
g.DrawImage(imgSource, 0, 0);
return imgTarget;
}
您需要先将背景绘制为您想要的颜色:
public static Image CropToCircle(Image srcImage, Color backGround)
{
Image dstImage = new Bitmap(srcImage.Width, srcImage.Height, srcImage.PixelFormat);
Graphics g = Graphics.FromImage(dstImage);
using (Brush br = new SolidBrush(backGround)) {
g.FillRectangle(br, 0, 0, dstImage.Width, dstImage.Height);
}
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, dstImage.Width, dstImage.Height);
g.SetClip(path);
g.DrawImage(srcImage, 0, 0);
return dstImage;
}
测试代码:
Image srcImage = Bitmap.FromFile(@"..\..\080.jpg");
Image dstImage = CropToCircle(srcImage, Color.CadetBlue);
dstImage.Save(@"..\..\080cropped.jpg", ImageFormat.Jpeg);
Input:
![enter image description here](https://i.stack.imgur.com/Qnmm5.jpg)
Output:
![enter image description here](https://i.stack.imgur.com/eg6cg.jpg)
如果您希望图像的外部是透明的,那么您需要将像素格式设置为带有 Alpha 通道的像素格式(而不是 srcImage 的像素格式),并使用包含全透明 Alpha 的背景颜色。保存时,请确保使用支持 alpha 的文件格式(例如 png)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)