.Net Core 中使用SkiaSharp绘制图片
引入SkiaSharp nuget包
使用代码
public class SkiaSharpHelper
{
/// <summary>
/// 将文字加到图片上
/// </summary>
/// <param name="templateFilePath">模板图片路径</param>
/// <param name="filepath">保存文件路径</param>
/// <returns></returns>
public static (bool result, string msg) CreateImgByTemplate(string templateFilePath,string filepath)
{
string msg = string.Empty;
try
{
if (!File.Exists(templateFilePath))
{
throw new Exception("模板文件不存在");
}
using (var bmp = SKBitmap.Decode(templateFilePath))
{
//初始化画布
var canvas = new SKCanvas(bmp);
var paint = new SKPaint()
{
Color = SKColors.White,
IsAntialias = true, // 抗锯齿
Style = SKPaintStyle.Fill,
//TextAlign = SKTextAlign.Center,
TextSize = 16f,
Typeface = SKTypeface.FromFamilyName("Microsoft YaHei", SKFontStyle.Bold)
};
int x = 30;
int y = 30;
canvas.DrawText("hello world!!!", x, y * (1.2f), paint);
using (var image = SKImage.FromBitmap(bmp))
{
using (var writeStream = File.OpenWrite(filepath))
{
image.Encode(SKEncodedImageFormat.Png, 80).SaveTo(writeStream); // 保存文件
return (true, msg);
}
}
}
}
catch (Exception ex)
{
msg = ex.ToString();
LogHelper.WriteLog(ex);
return (false, msg);
}
}
/// <summary>
/// 创建验证码图片
/// </summary>
/// <param name="filepath">保存文件路径</param>
/// <returns></returns>
public static (bool result, string msg) CreateImg(string filepath)
{
string msg = string.Empty;
try
{
using (var surface = SKSurface.Create(new SKImageInfo(100, 80)))
{
var canvas = surface.Canvas;
canvas.Clear(SKColors.Blue);
var paint = new SKPaint()
{
Color = SKColors.Red,
IsAntialias = true, // 抗锯齿
Style = SKPaintStyle.Fill,
TextAlign = SKTextAlign.Center,
TextSize = 16f,
Typeface = SKTypeface.FromFamilyName("Microsoft YaHei", SKFontStyle.Bold)
};
var coord = new SKPoint(50, 48);
canvas.DrawText("my text", coord, paint);
using (var image = surface.Snapshot())
{
using (var writeStream = System.IO.File.OpenWrite(filepath))
{
image.Encode(SKEncodedImageFormat.Png, 80).SaveTo(writeStream);
}
}
}
}
catch (Exception ex)
{
msg = ex.ToString();
LogHelper.WriteLog(ex);
return (false, msg);
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2022-07-12 vue.js 三种方式安装(vue-cli)
2022-07-12 cnpm安装步骤
2022-07-12 npm 源地址设置及恢复
2022-07-12 Window下完全卸载删除Nodejs
2022-07-12 No installations recognized 以及 nvm use切换node版本无效的解决办法
2022-07-12 使用 nvm 管理不同版本的 node 与 npm