Igor Cova
Igor Cova

Reputation: 3514

C# .net Core rounded corners for image

I save images from social networks and I want to do rounded corners for image and save it to the database. For example, I got a photo from the facebook by url on my Api and I want to process this image

How it possible on .net Core

Below, what results I expect

Image before:

enter image description here

Image after:

enter image description here

Upvotes: 3

Views: 1893

Answers (1)

koryakinp
koryakinp

Reputation: 4125

You can use SixLabors.ImageSharp library, it is available for .NET Core:

PM > Install-Package SixLabors.ImageSharp

Here is the sample code:

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));
}

And you can use it like this:

 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");
     }
 }

More examples can be found here.

Upvotes: 3

Related Questions