注意:这里的文档为最新版的 SixLabors.ImageSharp 2.xx 和 SixLabors.ImageSharp.Drawin 1.0.0-beta15
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 = SystemFonts.Families.FirstOrDefault(); FontFamily boldFontFamily = SystemFonts.Families.FirstOrDefault() ; var fonts = new FontCollection(); var fonts2 = new FontCollection(); if(File.Exists("./fonts/MiSans-Normal.ttf")) { normalFontFamily = fonts.Add("./fonts/MiSans-Normal.ttf"); } if(File.Exists("./fonts/MiSans-Medium.ttf")) { boldFontFamily = fonts2.Add("./fonts/MiSans-Medium.ttf"); }
使用
var templatePath = "./images/bg.png"; var outputImage = Image.Load(templatePath); var ms = new MemoryStream(); // 先画标题 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 textOptions = new TextOptions(font) { TabWidth = 16, VerticalAlignment = VerticalAlignment.Top, HorizontalAlignment = HorizontalAlignment.Left, WrappingLength = 650 }; var size = TextMeasurer.Measure(title, textOptions); if (size.Width > 650) { if (size.Width > 850) { top = 270; } fontSize = 48; font = new Font(boldFontFamily, fontSize, FontStyle.Bold); } textOptions.Origin = new PointF(70, top); textOptions.Font = font; outputImage.Mutate(o => { o.DrawText(textOptions, title, font, color); }); // 再画要求 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)); textOptions.Font = font; outputImage.Mutate(o => { textOptions.Origin = new PointF(70, 420); o.DrawText(textOptions, "奖励金额:最低奖励" + (minAward > decimal.Zero ? minAward : '-') + "元", font, color); textOptions.Origin = new PointF(70, 470); o.DrawText(textOptions, "粉丝要求:" + (task.FanCount == 0 ? "不限" : task.FanCount), font, color, ); textOptions.Origin = new PointF(70, 520); o.DrawText(textOptions, "报名名额:" + (task.Qquota == 0 ? "不限" : task.Qquota + " 人"), font, color, ); }); outputImage.SaveAsJpeg(ms); return new FileContentResult(ms.ToArray(), @"image/jpeg");
目前尚无回复