一.安装System.Drawing.Common库
工具->NuGet 包管理->程序包管理控制台
输入命令
Install-Package System.Drawing.Common
二.代码案例实现
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace Web.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class UploadController : ControllerBase
{
[HttpPost]
public void UploadFile([FromForm] FileViewModel fileViewModel)
{
string outputImagePath = @"C:\Users\Desktop\watermark.jpg"; // 输出图片路径
string watermarkText = "水印文字 2024";
AddWatermark(fileViewModel.file, outputImagePath, watermarkText);
}
void AddWatermark(IFormFile file, string outputImagePath, string watermarkText)
{
using (Image image = IFormFileToImage(file))
using (Graphics graphic = Graphics.FromImage(image))
{
Font font = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Pixel);
Color color = Color.FromArgb(128, 128, 128); // 浅灰色
SolidBrush brush = new SolidBrush(color);
PointF point = new PointF(image.Width - 160, image.Height - 35); // 水印位置
// 设置文字抗锯齿
graphic.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
// 绘制水印
graphic.DrawString(watermarkText, font, brush, point);
// 保存图片
image.Save(outputImagePath, ImageFormat.Png);
}
}
/// <summary>
/// IFormFile文件转Image
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
Image IFormFileToImage(IFormFile file)
{
using (var memoryStream = new MemoryStream())
{
file.CopyTo(memoryStream);
memoryStream.Position = 0;
return Image.FromStream(memoryStream);
}
}
}
public class FileViewModel
{
public IFormFile file { get; set; }
}
}
三.上传图片
四.实现效果
右下角 ‘水印文字 2024’就是刚刚打的水印
标签:Core,image,System,水印,file,using,NET,Drawing From: https://blog.csdn.net/qq_45082171/article/details/139142781