注意:这里的文档再最新版的 SixLabors.ImageSharp 2.xx 和 SixLabors.ImageSharp.Drawin 1.0.0-beta15 里已经废弃了,不能用了。
最新版地址在 https://www.twle.cn/t/90557
Asp.Net Core 跨平台使用图像库,推荐使用 SixLabors.ImageSharp
。原因呢,简单、快平台 (相对于 System.Draw.Common
安装
对了,在安装时一定要打开 include prereleases,不然你看不到 SixLabors.ImageSharp.Drawing
首先下载自定义字体
自定义字体方面,我推荐使用小米最近刚出的可商用的字体 MiSans。
下载地址
https://kpan.mioffice.cn/webfolder/ext/IUrT%23akFnZ0%40?n=0.3820181893993342
密码:8D40
我尝试过阿里的那个啥字体,但是感觉少了什么东西,字都粘到一块了。还是用小米的吧
下载完后放在当前目录下的 fonts
目录
加载字体
我们要做的事,就是如果存在自定义字体则使用自定义字体,如果没有则使用系统默认的 Arial
FontFamily normalFontFamily = null; FontFamily boldFontFamily = null; var fonts = new FontCollection(); if(File.Exists("./fonts/MiSans-Normal.ttf")) { normalFontFamily = fonts.Install("./fonts/MiSans-Normal.ttf"); } else { normalFontFamily = SystemFonts.Families.FirstOrDefault(); } if(File.Exists("./fonts/MiSans-Medium.ttf")) { boldFontFamily = fonts.Install("./fonts/MiSans-Medium.ttf"); } else { boldFontFamily = SystemFonts.Families.FirstOrDefault(); }
使用
var templatePath = "./images/bg.png"; var outputImage = Image.Load(templatePath); var ms = new MemoryStream(); var textOptions = new TextOptions() { TabWidth = 16, ApplyKerning = true, VerticalAlignment = VerticalAlignment.Top, HorizontalAlignment = HorizontalAlignment.Left, WrapTextWidth = 650 }; var graphicsOptions = new GraphicsOptions() { Antialias = true }; var options = new DrawingOptions() { GraphicsOptions = graphicsOptions, TextOptions = textOptions }; // 先画标题 var title = task.Title; var color = new Color(new Bgr24(195, 99, 21)); var top = 300; var fontSize = 64; var font = new Font(boldFontFamily, fontSize, FontStyle.Bold); var size = TextMeasurer.Measure(title, new RendererOptions(font)); if (size.Width > 650) { if (size.Width > 850) { top = 270; } fontSize = 48; font = new Font(boldFontFamily, fontSize, FontStyle.Bold); } outputImage.Mutate(o => { o.DrawText(options, title, font, color, new PointF(70, top)); }); // 再画要求 decimal minAward = decimal.Zero; if (task.Award != null) { if (task.Award.RewardConfigs != null && task.Award.RewardConfigs.Count > 0) { var awards = task.Award.RewardConfigs.OrderBy(x => x.Money).ToList(); if (awards[0].Money > 0) minAward = awards[0].Money; } } font = new Font(normalFontFamily, 36, FontStyle.Bold); color = new Color(new Rgb24(189, 117, 46)); outputImage.Mutate(o => { o.DrawText(options, "奖励金额:最低奖励" + (minAward > decimal.Zero ? minAward : '-') + "元", font, color, new PointF(70, 420)); o.DrawText(options, "粉丝要求:" + (task.FanCount == 0 ? "不限" : task.FanCount), font, color, new PointF(70, 470)); o.DrawText(options, "报名名额:" + (task.Qquota == 0 ? "不限" : task.Qquota + " 人"), font, color, new PointF(70, 520)); }); outputImage.SaveAsJpeg(ms); return new FileContentResult(ms.ToArray(), @"image/jpeg");
目前尚无回复