Asp.Net Core 使用 SixLabors 生成圆形或圆角头像/图片

yufei       2 年, 3 月 前       2260

Asp.Net Core 跨平台使用图像库,推荐使用 SixLabors.ImageSharp。原因呢,简单、快平台 (相对于 System.Draw.Common

安装

2022_01_03_sixlabors_imageshape.jpeg

对了,在安装时一定要打开 include prereleases,不然你看不到 SixLabors.ImageSharp.Drawing

自定义圆形头像助手

SixLabors.ImageSharp.Drawing 没有那只生成圆形图像的函数,但是人家底层库支持,所以我们只需要封装一下,搞一个助手出来即可

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Drawing.Processing;

using System;
using System.Collections.Generic;
using System.Text;

namespace HaoShuaShua.Application.Share.Helpers
{
    public static class CupCircularHelper
    {
        public static Image ShareImg(String templatePath, String logoPath, Point position, int logoWidth, int cornerRadius)
        {

            var outputImage = Image.Load(templatePath);
            if (outputImage.Size().Width != 1080)
            {
                outputImage.Mutate(x => x.Resize(1080, 1920));
            }

            var logo = Image.Load(logoPath);

            logo.Mutate(x => x.ConvertToAvatar(new Size(logoWidth, logoWidth), cornerRadius));
            outputImage.Mutate(x => x.DrawImage(logo, position, 1));
            return outputImage;
        }

        public static Image ShareImg(String templatePath, byte[] logoByteData, Point position, int logoWidth, int cornerRadius)
        {

            var outputImage = Image.Load(templatePath);

            if(outputImage.Size().Width != 1080)
            {
                outputImage.Mutate(x => x.Resize(1080, 1920));
            }

            var logo = Image.Load(logoByteData);

            logo.Mutate(x => x.ConvertToAvatar(new Size(logoWidth, logoWidth), cornerRadius));
            outputImage.Mutate(x => x.DrawImage(logo, position, 1));
            return outputImage;
        }

        // Implements a full image mutating pipeline operating on IImageProcessingContext
        private static IImageProcessingContext ConvertToAvatar(this IImageProcessingContext processingContext, Size size, float cornerRadius)
        {
            return processingContext.Resize(new ResizeOptions
            {
                Size = size,
                Mode = ResizeMode.Crop
            }).ApplyRoundedCorners(cornerRadius);
        }


        // This method can be seen as an inline implementation of an `IImageProcessor`:
        // (The combination of `IImageOperations.Apply()` + this could be replaced with an `IImageProcessor`)
        private static IImageProcessingContext ApplyRoundedCorners(this IImageProcessingContext ctx, float cornerRadius)
        {
            Size size = ctx.GetCurrentSize();
            IPathCollection corners = BuildCorners(size.Width, size.Height, cornerRadius);

            ctx.SetGraphicsOptions(new GraphicsOptions()
            {
                Antialias = true,
                AlphaCompositionMode = PixelAlphaCompositionMode.DestOut // enforces that any part of this shape that has color is punched out of the background
            });

            // mutating in here as we already have a cloned original
            // use any color (not Transparent), so the corners will be clipped
            foreach (var c in corners)
            {
                ctx = ctx.Fill(Color.Red, c);
            }
            return ctx;
        }

        private static IPathCollection BuildCorners(int imageWidth, int imageHeight, float cornerRadius)
        {
            // first create a square
            var rect = new RectangularPolygon(-0.5f, -0.5f, cornerRadius, cornerRadius);

            // then cut out of the square a circle so we are left with a corner
            IPath cornerTopLeft = rect.Clip(new EllipsePolygon(cornerRadius - 0.5f, cornerRadius - 0.5f, cornerRadius));

            // corner is now a corner shape positions top left
            //lets make 3 more positioned correctly, we can do that by translating the original around the center of the image

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

            // move it across the width of the image - the width of the shape
            IPath cornerTopRight = cornerTopLeft.RotateDegree(90).Translate(rightPos, 0);
            IPath cornerBottomLeft = cornerTopLeft.RotateDegree(-90).Translate(0, bottomPos);
            IPath cornerBottomRight = cornerTopLeft.RotateDegree(180).Translate(rightPos, bottomPos);

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

}

上面的函数中 ConvertToAvatar() 是实际用来生成圆形或者圆角头像的,而 ShareImg 则是实际用来生成分享图的

使用方式

string bgFullPath = ""./image/bg.png";
string logoFullPath = "./image/logo.png";
var position = new Point(374, 1365);
var logoWidth = 300;
var cornerRadius = 15;

Image outputImage = CupCircularHelper.ShareImg(bgFullPath, logoFullPath, position, logoWidth, cornerRadius);

var ms = new MemoryStream();
outputImage.SaveAsJpeg(ms);
return new FileContentResult(ms.ToArray(), @"image/jpeg");
目前尚无回复
简单教程 = 简单教程,简单编程
简单教程 是一个关于技术和学习的地方
现在注册
已注册用户请 登入
关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.