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