Nuget 安装 System.Drawing.Common
加文字
public string SaveImage(IFormFile image)
{
// 准备好保存图片的文件夹
var fileName = image.FileName.Replace("\\", "/").ToLower();
var pathFormat = "/content/article/image/{yyyy}{mm}{dd}/{time}{rand:6}";
var fileLogicPath = ZRui.Web.Common.FileUtils.PathFormat(System.IO.Path.GetFileName(fileName), pathFormat);
string localPath = environment.MapWebPath(fileLogicPath);
FileUtils.CreateDirectory(localPath);
// 主代码
using (var stream = new MemoryStream())
{
// 把数据从IFormFile中取出来
image.CopyTo(stream);
// 创建Image
using var tempImage = Image.FromStream(stream);
// 创建图层
using var graphic = Graphics.FromImage(tempImage);
// 准备好将要画的字符串的字体、大小、颜色等
using var font = new Font(FontFamily.GenericSansSerif, 18, FontStyle.Bold, GraphicsUnit.Pixel);
var color = Color.FromArgb(128, 255, 255, 255);
using var brush = new SolidBrush(color);
// 要把字符串画在哪个位置,下面是画在右下角
var point = new Point(tempImage.Width - 120, tempImage.Height - 30);
// 在图层上画字符串
graphic.DrawString("cscoder.cn", font, brush, point);
// 创建文件流
using var fileStream = new FileStream(localPath, System.IO.FileMode.CreateNew);
// 把图片数据写入到文件流
tempImage.Save(fileStream, ImageFormat.Jpeg);
}
return fileLogicPath;
}