第一次写博客,直接上代码:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AddImageText
{
class Program
{
static void Main(string[] args)
{
string imagePath = “C:/Users/Administrator/Desktop/123/”;
Test(imagePath);
Console.ReadKey();
}
public static void Test(string path)
{
DirectoryInfo folder = new DirectoryInfo(path);
FileSystemInfo[] files = folder.GetFileSystemInfos();
int length = files.Length;
for (int i = 0; i < length; i++)
{
string childPath = files[i].FullName;
Console.WriteLine(childPath);
// Console.ReadKey();
Image image = Image.FromFile(childPath);
drawText(files[i].Name,image, i.ToString(), "微软雅黑", 80, FontStyle.Regular, image .Width,image .Height);
}
}
/// <summary>
/// 在现有画布上添加文字
/// </summary>
/// <param name="PathName">输出路径</param>
/// <param name="image"></param>
/// <param name="txt">添加的文字</param>
/// <param name="fontName">字体名称</param>
/// <param name="fontSize">字体大小</param>
/// <param name="fontStyle">字体风格</param>
/// <param name="x"></param>
/// <param name="y"></param>
public static void drawText(string PathName, Image image, string txt, string fontName, int fontSize, FontStyle fontStyle, int x, int y)
{
Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
Graphics g = Graphics.FromImage(bitmap);
//设置图像质量
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//文字绘制
Font font = new Font(fontName, fontSize, fontStyle, GraphicsUnit.Pixel);
Brush brush = new SolidBrush(Color.Blue);
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault;
g.DrawString("第"+txt +"页", font, brush, new Rectangle(2800, 2350, x, y), StringFormat.GenericDefault);
Console.WriteLine("绘制完成");
string Outpath = "C:/Users/Administrator/Desktop/456/";
bitmap.Save(Outpath + PathName, System.Drawing.Imaging.ImageFormat.Gif);
g.Dispose();
}
}
}
使用方法:桌面上新建一个名称为123的文件夹,放入需要添加文字的图片。新建一个名称为456的文件夹,该文件夹为输出路径,点击运行就好。
注:需要引入一个dll文件: System.Drawing.dll,右侧右键点击“引入“——添加引用——搜索 添加
参考:参考链接