gpt4 book ai didi

图像的 C# .net Core 圆角

转载 作者:行者123 更新时间:2023-12-05 04:04:11 26 4
gpt4 key购买 nike

我从社交网络保存图像,我想为图像做圆角并将其保存到数据库中。例如,我通过url从 Facebook 上得到了一张照片。在我的 Api 上,我想处理这张图片

.net Core 如何实现

下面是我期望的结果

之前的图片:

enter image description here

之后的图像:

enter image description here

最佳答案

您可以使用 SixLabors.ImageSharp 库,它可用于 .NET Core:

PM > Install-Package SixLabors.ImageSharp

示例代码如下:

public static void ApplyRoundedCorners(Image<Rgba32> img, float cornerRadius)
{
IPathCollection corners = BuildCorners(img.Width, img.Height, cornerRadius);
var graphicOptions = new GraphicsOptions(true) { BlenderMode = PixelBlenderMode.Src };
img.Mutate(x => x.Fill(graphicOptions, Rgba32.Transparent, corners));
}

public static IPathCollection BuildCorners(int imageWidth, int imageHeight, float cornerRadius)
{
var rect = new RectangularPolygon(-0.5f, -0.5f, cornerRadius, cornerRadius);

IPath cornerToptLeft = rect.Clip(new EllipsePolygon(cornerRadius - 0.5f, cornerRadius - 0.5f, cornerRadius));

var center = new Vector2(imageWidth / 2F, imageHeight / 2F);

float rightPos = imageWidth - cornerToptLeft.Bounds.Width + 1;
float bottomPos = imageHeight - cornerToptLeft.Bounds.Height + 1;

IPath cornerTopRight = cornerToptLeft.RotateDegree(90).Translate(rightPos, 0);
IPath cornerBottomLeft = cornerToptLeft.RotateDegree(-90).Translate(0, bottomPos);
IPath cornerBottomRight = cornerToptLeft.RotateDegree(180).Translate(rightPos, bottomPos);

return new PathCollection(cornerToptLeft, cornerBottomLeft, cornerTopRight, cornerBottomRight);
}

private static IImageProcessingContext<Rgba32> ConvertToAvatar(this IImageProcessingContext<Rgba32> processingContext, Size size, float cornerRadius)
{
return processingContext.Resize(new ResizeOptions
{
Size = size,
Mode = ResizeMode.Crop
}).Apply(i => ApplyRoundedCorners(i, cornerRadius));
}

你可以这样使用它:

 using (var img = Image.Load("fb.jpg"))
{
using (Image<Rgba32> destRound = img.Clone(x => x.ConvertToAvatar(new Size(200, 200), 100)))
{
destRound.Save("output/fb-round.png");
}
}

可以找到更多示例here .

关于图像的 C# .net Core 圆角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53023913/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com